我有一个像这样的块:
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
这是我到目前为止所做的:
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
我收到错误:
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)>'
我该如何正确测试救援?
答案 0 :(得分:0)
您必须指定一个特定的异常类,否则rspec会在检测到异常后立即保释;但是,如果没有从Exception中拯救,你可以做到这一点(正如Nick的评论所指出的那样)。
class MyCustomError < StandardError; end
begin
response = Facebook.make_profile_request(params[:token])
rescue MyCustomError => e
...
end
在您的规范中,您应该使存根返回自定义错误类。像这样:
Facebook.stub(:make_profile_request).with(fb_token).and_raise(MyCustomError)
答案 1 :(得分:-1)
我最近遇到过类似的问题。
如果您更改了代码
rescue => e
到
rescue Exception => e
您的测试用例将通过。