Take the 2-minute tour ×

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:

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

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!

share|improve this question
I don't think it's Ruby problem? You use RSpec, am I right? –  Michal Szyndel Jul 15 '13 at 17:20

1 Answer 1

up vote 1 down vote accepted

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
    Resque.redis.select 1
  rescue Exception

# same for config.after(:all)
share|improve this answer
Thank you so much! That explains quite a bit –  NcAdams Jul 15 '13 at 17:44
I would caution against catching Exception. There're certain things such as StandardError that it will also catch and you won't know about it at all. –  Hengjie Oct 4 '13 at 21:11

Your Answer


