【问题标题】:Writing tests for custom error pages in Rails在 Rails 中为自定义错误页面编写测试
【发布时间】:2016-02-14 17:28:18
【问题描述】:

我已经在我的 Rails 应用程序中为各种错误代码实现了自定义错误页面,如下所示:

config/routes.rb

Rails.application.routes.draw do
  # ...

  [400, 401, 403, 404, 405, 406, 418, 422, 500, 503].each do |status|
    get "/#{status}", to: "application#render_error", status: status
  end 
end

app/controllers/application_controller.rb

class ApplicationController < ActionController::API
  # ...

  # Render an error status using JSON.
  def render_error(status=nil)
    # If there's no status, try and get it from the params, which will be the case with the error routes.
    status ||= params[:status]

    message = error_message(status)
    render json: { error: message }, status: status
  end

  def error_message(status):
    # Return a simple error message.
  end
end

到目前为止,这运行良好,因为未找到的错误会使用我设置的错误路由自动呈现,我可以使用 render_error 手动呈现错误。

我尝试为这些编写测试,但我无法找出正确的(或任何)方法。这是我迄今为止尝试过的:

class ApplicationControllerTest < ActionController::TestCase

  test "Default error route should return correct status code" do
    get "/418"
    assert_response 418
  end

  test "render_error should return correct status code" do
    render_error 418
    assert_response 418
  end
end

由于测试无法将/418 解释为application 控制器的操作,因此第一个失败。第二个失败,因为测试找不到render_error 方法。

我应该如何编写测试来正确测试这些?

【问题讨论】:

    标签: ruby-on-rails unit-testing error-handling controller http-error


    【解决方案1】:

    您在此处使用的功能测试用于testing the actions within a particular controller。由于这些操作没有在您的 ApplicationController 中专门定义,因此您遇到了问题。

    您可以将这些测试重写为 integration tests(保存在 test/integration/ 文件夹中),如下所示:

    class ErrorsTest < ActionDispatch::IntegrationTest
    
      test "Default error route should return correct status code" do
        get "/418"
        assert_response 418
      end
    
    end 
    

    这有点不标准,因为集成测试通常用于测试多个控制器的交互......即您的应用程序的流程。

    我个人更喜欢Rspec,并将这些写成request specs

    【讨论】:

    • 看起来集成测试可以完成这项工作(我将研究使用 RSpec);但是第二个我收到undefined method `render_error';如何使 render_error 对测试可见?
    • 如果你的路由定义会将错误状态码传递给该方法,为什么还要在这里测试render_error方法呢?您已经在测试正确的响应...
    • 我想测试当我将自定义错误代码传递给它呈现正确响应的方法时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多