代码之家  ›  专栏  ›  技术社区  ›  Simon

如何测试路由故障的救援功能?

  •  0
  • Simon  · 技术社区  · 14 年前

    在我们的rails 2.3应用程序中,我为路由错误设置了一个解救工具,如下所示:

    rescue_from ActionController::RoutingError,       :with => :redirect_or_render_error
    rescue_from ActionController::UnknownController,  :with => :redirect_or_render_error
    rescue_from ActionController::UnknownAction,      :with => :redirect_or_render_error
    

    redirect_or_render_error 方法我重定向某些URL(从数据库中提取,因此不能只使用routes.rb),我想测试一下。我是在索引页的功能测试中做的(这是正确的位置吗?)因此:

    @request.remote_addr = '12.34.56.78' # fake remote request
    get '/example'
    assert_redirected_to '/example_things/123456'
    

    ActionController::RoutingError: No route matches {:action=>"/example", :controller=>"home"}
    

    即使它在发展中起作用。如何测试路由故障的救援功能?

    2 回复  |  直到 14 年前
        1
  •  0
  •   Steve Ross    14 年前

    你在断言你的路线是正确的。事实并非如此。您有一组计划不映射的路由,将在异常处理程序中处理这些路由。(旁白:我认为您应该尽量在routes.rb中处理尽可能多的情况,并让普通的Ruby方法来处理任何进一步的操作。)

    在任何情况下,要真正测试这一点,您需要按照以下思路执行更多操作:

    @request.remote_addr = '12.34.56.78' # fake remote request
    assert_raise ActionController::RoutingError do
      get '/example'
    end
    
        2
  •  0
  •   Simon    14 年前

    结果我不得不使用集成测试,而不是功能测试,如下所示:

    get '/example', {}, :remote_addr => '12.34.56.78'
    assert_redirected_to '/example_things/123456'
    

    config.action_controller.consider_all_requests_local 在config/environments/test.rb中设置为false