1

I have a block like this:

begin
  response = Facebook.make_profile_request(params[:token])
rescue => e
  Airbrake.notify(
     :error_class => "Facebook Processing",
     :error_message => "Error: #{e.message}"
   )

  flash[:notice] = "Uh oh...something went wrong. Please try again."
  redirect_to root_path
end

This is what I have so far:

it "should notify Airbrake if call to FB fails" do
  Facebook.stub(:make_profile_request).with(fb_token).and_raise(Exception)
  Airbrake.should_receive(:notify)
  get :facebook_process, token: fb_token
end

I get error:

  1) UsersController GET facebook_process should notify Airbrake if call to FB fails
 Failure/Error: get :facebook_process, token: fb_token
 Exception:
   Exception
 # ./app/controllers/users_controller.rb:9:in `facebook_process'
 # ./spec/controllers/users_controller_spec.rb:41:in `block (3 levels) in <top (required)>'

How should I properly test rescue?

user577808
  • 2,317
  • 4
  • 21
  • 31

2 Answers2

0

You have to specify a specific exception class, otherwise rspec will bail as soon as it detects the exception; but, here is how you can do it without rescuing from Exception (as pointed out in Nick's comment).

class MyCustomError < StandardError; end

begin
  response = Facebook.make_profile_request(params[:token])
rescue MyCustomError => e
  ...
end

And in your spec, you should make the stub return the custom error class. Something like this:

Facebook.stub(:make_profile_request).with(fb_token).and_raise(MyCustomError)
Javid Jamae
  • 8,741
  • 4
  • 47
  • 62
  • 1
    You'd also need to change the stub to return the custom error class. – zetetic Jun 02 '15 at 23:37
  • Using `stub` from rspec-mocks' old `:should` syntax without explicitly enabling the syntax is deprecated. Use the new `:expect` syntax or explicitly enable `:should` instead. – Ziggy Aug 20 '15 at 20:05
-2

I have faced the similar issue recently.

if you change your code

rescue => e

to

rescue Exception => e

your test case will pass.

Soundar Rathinasamy
  • 6,658
  • 6
  • 29
  • 47
  • 6
    This is a bad idea: http://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby – Nick Jun 27 '13 at 18:54
  • If you think it is bad idea you are welcome to give the good idea as your answer. – Soundar Rathinasamy Jun 28 '13 at 07:01
  • Unfortunately I don't have the answer. That's how I arrived here - in search of a solution. That being said, even though I don't have the answer, it's worthwhile warning readers of bad practice. – Nick Jun 28 '13 at 19:25
  • @Nick You are raising `Exception` in your spec, which isn't normally caught by `rescue`. Raise something more specific in the spec. – Dean Brundage Oct 29 '13 at 02:43
  • @DeanBrundage Just to note, I'm not the person that asked the question, so it wasn't my test. However, you make a good point - you could raise a `RuntimeError` which should be caught by `rescue`. – Nick Oct 29 '13 at 11:35