【发布时间】: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