我有一个方法,如果它做对了,我想测试不同的参数。 我现在正在做的是
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
但是,重复这个方法一次又一次真的不是那么干......什么是更好的方法来实现这一目标?更像黄瓜的“table”选项的方式(它只是帮助方法的正确行为,所以使用黄瓜似乎不正确)。
答案 0 :(得分:1)
你的方法需要3个参数,但你传递了两个参数。
话虽这么说,你可以编写一个循环来多次调用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
这样,你只有一个例子(又名it
调用),你的例子被提取到一个数据表(包含哈希的数组)。
答案 1 :(得分:1)
我认为如果删除实例变量@ex_string的传递,你的方法就可以了。 (并且匹配仅在test_method_with
中发生,正如Kenrick建议的那样。)那说你可以使用自定义匹配器:
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
可以将匹配器放在规范帮助文件中,以便从多个规范进行访问。