5

在我的Rails 3.2應用程序中,我試圖使用config.exceptions_app來路由異常通過路由表來呈現錯誤特定的頁面(尤其是401 forbidden)。下面是我到目前爲止得到了配置:如何使config.exceptions_app與rspec一起工作

# application.rb 
config.action_dispatch.rescue_responses.merge!('Error::Forbidden' => :forbidden) 
config.exceptions_app = ->(env) { ErrorsController.action(:show).call(env) } 

# development.rb 
config.consider_all_requests_local  = false 

# test.rb 
config.consider_all_requests_local  = false 

而現在問題的肉:

module Error 
    class Forbidden < StandardError 
    end 
end 

class ErrorsController < ApplicationController 
    layout 'error' 

    def show 
    exception  = env['action_dispatch.exception'] 
    status_code  = ActionDispatch::ExceptionWrapper.new(env, exception).status_code 
    rescue_response = ActionDispatch::ExceptionWrapper.rescue_responses[exception.class.name] 

    render :action => rescue_response, :status => status_code, :formats => [:html] 
    end 

    def forbidden 
    render :status => :forbidden, :formats => [:html] 
    end 
end 

當我想要呈現的是401的響應,我只是raise Error::Forbidden其中,在開發環境完美運作。但是,在運行的RSpec一個例子時,例如:

it 'should return http forbidden' do 
    put :update, :id => 12342343343 
    response.should be_forbidden 
end 

它悲慘的失敗:

1) UsersController PUT update when attempting to edit another record should return http forbidden 
    Failure/Error: put :update, :id => 12342343343 
    Error::Forbidden: 
    Error::Forbidden 

有人能幫助我理解爲什麼這並不在我的測試環境中工作?我可能在ApplicationController中放置#rescue_from,但如果我必須這樣做才能使我的測試工作,我不確定首先使用config.exceptions_app的要點。 : - \

編輯:作爲一種解決方法,我結束了把以下放在config/environments/test.rb末尾這很糟糕,但似乎工作正常。

module Error 
    def self.included(base) 
    _not_found = -> do 
     render :status => :not_found, :text => 'not found' 
    end 

    _forbidden = -> do 
     render :status => :forbidden, :text => 'forbidden' 
    end 

    base.class_eval do 
     rescue_from 'ActiveRecord::RecordNotFound', :with => _not_found 
     rescue_from 'ActionController::UnknownController', :with => _not_found 
     rescue_from 'AbstractController::ActionNotFound', :with => _not_found 
     rescue_from 'ActionController::RoutingError', :with => _not_found 
     rescue_from 'Error::Forbidden', :with => _forbidden 
    end 
    end 
end 

回答

2

config/environments/test.rb集:

config.action_dispatch.show_exceptions = true 
+0

感謝您的回答,但我已經在該文件中有該行,並沒有解決我的問題。如果我註釋掉上面顯示的錯誤模塊,則我的測試會返回失敗。 – 7over21

0

我有同樣的問題。小心你提出異常的地方。如果它在before_filter/before_action,您的異常將被吞下。將您的查找器代碼移至實際的方法中,並且您的例外應該顯示在您的規格中。