Reputation: 1198
I know that there is a way to have a stub return multiple different values like this:
subject.stub(:method_call.and_return(1,2,3)
But I was hoping something like this would be possible:
subject.stub(:method_call).and_raise(Exception).once
subject.stub(:method_call).and_return(1)
But I haven't found an elegant way to have the stub only raise an exception the first time it's called. Suggestions?
Upvotes: 5
Views: 1939
Reputation: 4879
The only way I know of to do this is with a counter variable like this:
counter = 0
times = 2
TestModel.any_instance.stub(:some_method) do
(counter += 1) <= times ? raise(Exception) : 1
end
Which will output like this:
test = TestModel.new
test.some_method
=> Exception
test.some_method
=> Exception
test.some_method
=> 1
Upvotes: 8