如何测试 Railsrescue_from?

发布于 2024-12-13 12:53:52 字数 623 浏览 4 评论 0原文

Rails 3 似乎忽略了我的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'

如何确保在测试中正确“捕获”它?

Rails 3 seems is ignoring my rescue_from handler so I cannot test my redirect below.

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

In both functional and integration tests, this rescue_from is ignored, and the error is raised:

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

How can I make sure this is properly 'caught' in a test?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秉烛思 2024-12-20 12:53:52

Rails 3 在中间件中处理 ActionController::RoutingError,因此 ApplicationController::rescue_from 不会看到异常。 Rails 核心团队建议在 routes.rb 底部使用包罗万象的路线 (GitHub 问题),直到他们决定修复。

一种选择是使用包罗万象的路由来处理路由错误,然后手动引发异常以命中 rescue_from (我关于此问题的博客文章中的代码):

# 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

Rails 3 handles ActionController::RoutingError in middleware, so ApplicationController::rescue_from doesn't see the exception. The Rails core team recommends using a catch-all route at the bottom of routes.rb (GitHub issue) until they decide on a fix.

One option is to use a catch-all route to handle routing errors then manually raise an exception to hit rescue_from (code 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文