简体   繁体   English

Rspec-Rails:使用许多参数组合测试方法

[英]Rspec-Rails: Testing a method with a lot of combinations of arguments

I have a method that I want to test for different paramters if it does the right thing. 我有一个方法,我想测试不同的参数,如果它做正确的事情。 What I am doing right now is 我现在正在做的是

    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

But this is really not so DRY to repeat the method over and over again... What would be a better way to accomplish this? 但实际上并非如此彻底地重复这种方法......什么是更好的方法来实现这一目标? More in the way the "table" option of cucumber does it (it is just about the right behaviour of a helper method, so to use cucumber does not seem right). 更像黄瓜的“table”选项的方式(它只是帮助方法的正确行为,所以使用黄瓜似乎不对)。

Your method expects 3 arguments, but you're passing it two. 你的方法需要3个参数,但是你传递了两个参数。 That being said, you can write a loop to call it multiple times, like this: 话虽这么说,你可以编写一个循环来多次调用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

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). 这样,您只有一个示例(也就是it调用),并且您的示例被提取到数据表(包含散列的数组)。

I think your approach is fine if you remove the passing of the instance variable @ex_string. 如果你删除实例变量@ex_string的传递,我认为你的方法很好。 (And the match occurring only in test_method_with as Kenrick suggests.) That said you could use a custom matcher: (并且匹配仅发生在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

matchers can be placed in the spec helper file for access from several specs. 匹配器可以放在规范帮助文件中,以便从多个规范进行访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM