简体   繁体   中英

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).

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).

I think your approach is fine if you remove the passing of the instance variable @ex_string. (And the match occurring only in test_method_with as Kenrick suggests.) That said you could use a custom matcher:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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