NcAdams
NcAdams

Reputation: 2899

Ruby rescue doesn't catch a StandardError

I'm writing tests for a Ruby Rails application, and I have a block of code that is supposed to catch an error thrown by my Redis server if Ruby cannot connect to it. Currently, the code looks like this:

begin
    config.before(:all) { Resque.redis.select 1 }
    config.after(:all) { Resque.redis.keys("queue:*").each { |key| Resque.redis.del key } }
rescue Exception
    puts "RESCUED REDIS ERROR"
end

According to the stack trace when I try to run the tests, the second line of that code snippet -- config.before(:all) {...} -- throws a Redis::CannotConnectError. After a lot of "e.class.superclass.superclass..." commands, I determined that this error inherited from StandardError.

After that I got stuck. I tried catching the error with "rescue Redis::CannotConnectError", then "rescue", and finally "rescue Exception", but the error is still thrown. However, I tried the same things in the Ruby command prompt, and the exception was caught every time

Could anyone help me work out what's happening here? Thanks!

Upvotes: 1

Views: 1066

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124429

The problem is that the blocks passed to before and after are not being executed at the time they're defined; instead, they're being stored and then called later by Rspec before and after each spec file runs.

You'll probably want to move the begin/rescue within the blocks instead:

config.before(:all) do
  begin
    Resque.redis.select 1
  rescue Exception
    puts "RESCUED REDIS ERROR"
  end
end

# same for config.after(:all)

Upvotes: 1

Related Questions