I needed to have a method call return different results depending on the argument passed to it in RSpec today so I am putting a write up here on how this is done.
When stubbing a method in RSpec you can pass a block to it to determine the return value based on the input to the method.
I needed this because I needed to test the result of the nth invocation of the method.
Rspec implementation injection
Model.stub(:method_name) do |input|
false if input == "asdf"
false if input == "asdf2000"
false if input == "asdf1000"
false if input == "asdf1001"
false if input == "asdf1002"
false if input == "asdf1003"
true if input == "asdf1004"
end
result = Model.method_name(@arg1, @arg2, @arg3)
result.should == "asdf1004"
Leave a Reply