Tom
Tom

Reputation: 1105

rescue retry Ruby

Returning to Ruby after a long break, I'm trying to run a rescue retry block with an RSpec assertion with Capybara / Cucumber. I have the following which is purposely designed to fail to test my retry. It doesn't appear to be running the retry, I have gotten confused:

  begin
    retries ||= 2
    a = 1
    a.eql? 2 # false
    raise
  rescue
    puts 'Retrying assertion for failed step'
    retries -= 1
    if retries > 0
      sleep 0.5 # allows render of screen content
      retry
    end
  end

I do suspect I've written something wrong here. Is this the case?

Upvotes: 0

Views: 241

Answers (1)

Amadan
Amadan

Reputation: 198324

RSpec works by throwing RSpec::Expectations::ExpectationNotMetError when an expect fails. You are catching it with your unlimited rescue, so RSpec never sees it, which makes your test pass. Never ever use unlimited rescue. Always use a typed rescue, with the most general type being StandardError (not Exception!) - but make it as tight and specific as possible.

If you meant to catch ExpectationNotMetError and retry twice, then let it happen afterwards, you need to reraise it (using plain raise) for RSpec to see it, otherwise Ruby considers it to be handled and execution continues normally (and RSpec doesn't see it). You should still rescue it specifically, just to be safe from other possible errors you could do in the rescued block.


*) unless you know that exactly one thing can go wrong (and even then triple-check).

Upvotes: 2

Related Questions