2010-12-16 206 views
14

我如何測試rescue_from是RSpec?我想確保如果出現其中一個例外情況,控制器正確設置閃存並執行重定向。有沒有辦法模擬異常?RSpec:測試rescue_from

rescue_from PageAccessDenied do 
    flash[:alert] = "You do not have the necessary roles to access this page" 
    redirect_to root_url 
    end 

    rescue_from CanCan::AccessDenied do |exception| 
    flash[:alert] = exception.message 
    redirect_to root_url 
    end 

回答

14

假設你有一個authorize!方法引發異常,你應該能夠做這樣的事情:

describe "rescue_from exceptions" do 
    it "rescues from PageAccessDenied" do 
     controller.stub(:authorize!) { raise PageAccessDenied } 
     get :index 
     response.should redirect_to("/") 
     flash[:alert].should == "You do not have the necessary roles to access this page" 
    end 
    end 
+6

更好的解決方案:https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/anonymous-controller – kaihowl 2012-02-18 01:31:23

+0

我不明白stub ...對我來說,就像你讓控制器在測試中提出錯誤一樣。如果你只是在測試中僞造它,你怎麼能確定它會提高生產中的錯誤? – hamstar 2014-01-29 03:14:22

+0

@hamstar這隻測試'rescue_from'塊的行爲。爲了確保'authorize!'產生錯誤,你需要爲此寫另一個測試。據推測,這發生在一個圖書館(CanCan?),作者在那裏寫了測試。 – zetetic 2014-01-29 20:22:26