6

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

2
  • That's a really cool thing to test! Unfortunately I think it's going to be hard to do in rspec so maybe you can split it into two tests. One checking the retrying behaviour after failure and second checking the valid response behaviour? Jan 12, 2016 at 12:53
  • I did that, but I want to check that the retrying block I used actually works so after a few exceptions caught, it executes as it should and return the real value. Jan 12, 2016 at 12:57

2 Answers 2

7

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
0

Following @Ruy_Diaz suggestion you can also use the args to determine when to raise the error.

Example:

allow(Service).to receive(:run) do |args|
  raise MyError if args[:object].type == 'some_type_to_raise_error'

  response_that_the_service_is_expecting
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.