2012-01-05 79 views
1

我有這樣一個塊: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)>' 

應該如何我正確地測試救援?

+0

將您在測試存根中引發的異常更改爲'RuntimeError'之類的異常,因爲'rescue'沒有捕獲到該異常。 – 2013-10-29 02:42:04

回答

0

我最近遇到過類似的問題。

如果你改變你的代碼

rescue => e 

rescue Exception => e 

測試情況將成爲過去。

+5

這是一個壞主意:http://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby – Nick 2013-06-27 18:54:47

+0

如果你認爲這是個壞主意,你是歡迎給出好的想法作爲你的答案。 – 2013-06-28 07:01:31

+0

不幸的是我沒有答案。我就是這樣來到這裏的 - 尋找解決方案。這就是說,即使我沒有答案,但值得警告讀者不好的做法。 – Nick 2013-06-28 19:25:46

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

您還需要更改存根以返回自定義錯誤類。 – zetetic 2015-06-02 23:37:13

+0

不使用顯式啓用語法,使用rspec-mocks舊':should'語法中的'stub'已被棄用。請使用新的':expect'語法或顯式啓用':should'。 – Ziggy 2015-08-20 20:05:47