首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何测试Rails rescue_from?

如何测试Rails rescue_from?
EN

Stack Overflow用户
提问于 2011-11-04 00:44:29
回答 1查看 986关注 0票数 1

Rails 3似乎忽略了我的rescue_from处理程序,所以我无法在下面测试我的重定向。

代码语言:javascript
复制
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都被忽略,并引发错误:

代码语言:javascript
复制
ActionController::RoutingError: No route matches "/non_existent_url"
    test/integration/custom_404_test.rb:5:in `test_404'

我如何确保这在测试中被正确地“捕获”?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-28 19:19:09

Rails3在中间件中处理ActionController::RoutingError,所以ApplicationController::rescue_from看不到异常。Rails核心团队建议在routes.rb (GitHub issue)的底部使用通用路由,直到他们决定修复为止。

一种选择是使用捕获所有路由来处理路由错误,然后手动引发异常以命中rescue_from (code from my blog post about this issue):

代码语言:javascript
复制
# 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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7998637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档