问题
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