2012-12-05 52 views
0

我有一個方法,我想測試不同的參數,如果它做的是正確的。 我在做什麼,現在是Rspec-Rails:測試一個有很多參數組合的方法

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 

但這真的不是這麼幹的過度重複的方法,一遍又一遍......這將是一個更好的方式來做到這一點?更多的方式黃瓜的「表」選項(它只是一個輔助方法的正確行爲,所以使用黃瓜似乎不正確)。

回答

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

我認爲你的方法很好,如果你刪除了實例變量@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 

匹配器可以放置在規範助手文件的訪問從幾個規格。