Search code examples
ruby-on-railsruby-on-rails-4rspec

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


Solution

  • 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