簡體   English   中英

Rspec-Rails:使用許多參數組合測試方法

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

我有一個方法,我想測試不同的參數,如果它做正確的事情。 我現在正在做的是

    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”選項的方式(它只是幫助方法的正確行為,所以使用黃瓜似乎不對)。

你的方法需要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調用),並且您的示例被提取到數據表(包含散列的數組)。

如果你刪除實例變量@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

匹配器可以放在規范幫助文件中,以便從多個規范進行訪問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM