我如何使config.exceptions_app与rspec一起使用 [英] How do I make config.exceptions_app work with rspec
问题描述
在我的Rails 3.2应用程序中,我试图使用config.exceptions_app通过路由表路由异常以呈现特定于错误的页面(尤其是 401 Forbidden页面)。这是到目前为止我可以进行的配置:
In my Rails 3.2 app, I'm trying to use config.exceptions_app to route exceptions through the routing table to render error-specific pages (especially one for 401 Forbidden). Here's what I've got so far for configuration:
# 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中运行示例时,例如:
When I want to render that 401 response, I simply raise Error::Forbidden
which, in the development environment works perfectly. But when running an example in rspec, e.g.:
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 有什么意义。 code>首先。 :-\
Could someone help me understand why this doesn't work in my test environment? I could put a #rescue_from in ApplicationController, but if I have to do that to get my tests working, I'm not sure what the point of using config.exceptions_app
is in the first place. :-\
编辑:作为一种解决方法,我将以下内容放在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
推荐答案
在 config / environments / test.rb
中设置:
config.action_dispatch.show_exceptions = true
这篇关于我如何使config.exceptions_app与rspec一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!