1

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'

我怎样才能确保这在测试中被正确“捕获”?

4

1 回答 1

2

Rails 3 处理ActionController::RoutingError中间件,所以ApplicationController::rescue_from没有看到异常。routes.rbRails 核心团队建议在( GitHub issue )底部使用一条包罗万象的路线,直到他们决定修复。

一种选择是使用包罗万象的路由来处理路由错误,然后手动引发要命中的异常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
于 2012-04-28T11:19:08.980 回答