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

Your method expects 3 arguments, but you're passing it two. That being said, you can write a loop to call it multiple times, like this:

#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

This way, you only have one example (aka the it call) and your examples are extracted to a data table (the array containing the hashes).

于 2012-12-05T17:33:19.630 回答
1

如果您删除实例变量@ex_string 的传递,我认为您的方法很好。(并且匹配只发生在test_method_with肯里克建议的情况下。)也就是说你可以使用自定义匹配器:

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 回答