Rspec:测试救援块 [英] Rspec: Test rescue block
本文介绍了Rspec:测试救援块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的块:
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)>'
我应该如何正确测试救援?
How should I properly test rescue?
推荐答案
你必须指定一个特定的异常类,否则 rspec 会在检测到异常时立即退出;但是,这是在不从 Exception 中解救出来的情况下如何做到这一点(如 Nick 的评论中指出的).
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)
这篇关于Rspec:测试救援块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文