I want to use a rspec to simulate a flakey service handling.
For that, I want to make the service call raise an exception for a few times and after those times to return the real value.
Is this possible with rspec?
I tried with
allow(Service).to receive(:run).once.and_raise(MyError)
allow(Service).to receive(:run).once.and_return(response)
but on the first run it returns the response and not the error
You can accomplish this with a block implementation for the response.
call_count = 0
allow(Service).to receive(:run) do
call_count += 1
call_count < 3 ? raise(MyError) : response
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With