0

正しいことを行うかどうか、さまざまなパラメーターについてテストしたいメソッドがあります。私が今していることは、

    def test_method_with(arg1, arg2, match)
        it "method should #{match.inspect} when arg2 = '#{arg2}'" do
                method(arg1, FIXEDARG, arg2).should == match
        end
    end
    context "method with no info in arg1" do
        before (:each) do
            @ex_string = "no info"
        end
        test_method_with(@ex_string, "foo").should == "res1"}
        test_method_with(@ex_string, "bar").should == "res1"}
        test_method_with(@ex_string, "foobar").should == "res1"}
        test_method_with(@ex_string, "foobar2").should == "res2"}
        test_method_with(@ex_string, "barbar").should == "res2"}
        test_method_with(@ex_string, nil).should == nil}
    end

しかし、これは実際には、この方法を何度も繰り返すほどDRYではありません...これを達成するためのより良い方法は何でしょうか? キュウリの「テーブル」オプションがそれを行う方法の詳細 (これはヘルパー メソッドのほぼ正しい動作であるため、キュウリを使用することは正しくないようです)。

4

2 に答える 2

1

インスタンス変数 @ex_string の受け渡しを削除すれば、あなたのアプローチは問題ないと思います。(そして、test_method_withKenrick が示唆するようにのみ一致が発生します。)それは、カスタム マッチャーを使用できることを意味します。

RSpec::Matchers.define :match_with_method do |arg2, expected|
  match do
    method(subject, arg2) == expected
  end

  failure_message_for_should do
    "call to method with #{arg2} does not match #{expected}"
  end
end

it 'should match method' do
  "no info".should match_with_method "foo", "res1"
end

複数のスペックからアクセスするために、マッチャーをスペック ヘルパー ファイルに配置できます。

于 2012-12-05T21:57:58.510 に答える
1

メソッドは 3 つの引数を想定していますが、2 つ渡しています。そうは言っても、次のようにループを記述してit複数回呼び出すことができます。

#don't know what arg2 really is, so I'm keeping that name
[ {arg2: 'foo', expected: 'res1'},
  {arg2: 'bar', expected: 'res1'},
  #remaining scenarios not shown here
].each do |example|
  it "matches when passed some fixed arg and #{example[:arg2]}" do
     method(@ex_string, SOME_CONSTANT_I_GUESS,example[:arg2]).should == example[:expected]
  end
end

この方法では、1 つの例 (別名it呼び出し) だけがあり、例はデータ テーブル (ハッシュを含む配列) に抽出されます。

于 2012-12-05T17:33:19.630 に答える