2011-11-03 31 views
1

Rails 3似乎忽略了我的rescue_from處理程序,所以我無法在下面測試我的重定向。如何測試Rails rescue_from?

class ApplicationController < ActionController::Base 

    rescue_from ActionController::RoutingError, :with => :rescue_404 

    def rescue_404 
    flash[:notice] = "Error 404. The url <i>'#{env["vidibus-routing_error.request_uri"]}'</i> does not exist on this website." 
    redirect_to root_path 
    end 
end 

在功能和集成測試,這rescue_from被忽略,並引發錯誤:

ActionController::RoutingError: No route matches "/non_existent_url" 
    test/integration/custom_404_test.rb:5:in `test_404' 

我怎樣才能確保在測試,這是正確的「抓」?

回答

2

Rails 3在中間件中處理ActionController::RoutingError,所以ApplicationController::rescue_from沒有看到異常。 Rails核心團隊建議在routes.rbGitHub issue)的底部使用全線路由,直到他們決定修復爲止。

一種選擇是使用一個包羅萬象的途徑來處理路由錯誤,然後手動引發異常擊中rescue_fromcode from my blog post about this issue):

# routes.rb 
match "*path", :to => "application#routing_error" 

# application_controller.rb 
rescue_from ActionController::RoutingError, :with => :render_not_found 

def routing_error 
    raise ActionController::RoutingError.new(params[:path]) 
end 

def render_not_found 
    render :template => "misc/404" 
end 
相關問題