Rspec: Test rescue block

ε祈祈猫儿з 提交于 2021-01-28 18:24:05

问题


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?


回答1:


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)



回答2:


I have faced the similar issue recently.

if you change your code

rescue => e

to

rescue Exception => e

your test case will pass.



来源:https://stackoverflow.com/questions/8744494/rspec-test-rescue-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!