Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

raise an error on the xth time and after that return a value

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

like image 858
Nick Ginanto Avatar asked Jan 12 '16 12:01

Nick Ginanto


1 Answers

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
like image 174
Ruy Diaz Avatar answered Sep 28 '22 16:09

Ruy Diaz