我正在尝试通过第 404 和 500 页的测试用例。但是我遇到了很多问题
1) 首先,我在 app/views/errors/中有一个页面 500.html.erb 没有被调用。
2) 如果我运行下面的测试,我的系统卡住,我需要重新启动我的系统
3) 如果我评论这一行 expect{get "/errors/foo"}.to raise_exception(ActionController::RoutingError)。所以在我的 Controller 中,操作名称 page 500 被作为参数传递,但我的系统仍然卡住
谁能帮我解决这个问题
errors_spec.rb
require "spec_helper"
describe "Errors" do
before do
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("production"))
end
it "renders the 500 page" do
get "/errors/500"
expect(response.status).to eq(500)
end
it "renders the 404 page" do
get "/errors/404"
expect(response.status).to eq(404)
end
it "raises an exception if the page doesn't exist" do
expect {get "/errors/foo"}.to raise_exception(ActionController::RoutingError)
end
end
errors_controller.rb
class ErrorsController < ApplicationController
skip_before_filter :authenticate_user!
EXTERNAL_ERRORS = ['sso']
VALID_ERRORS = ['404', '403', '500', 'maintenance'] + EXTERNAL_ERRORS
def show
status = external_error? ? 500 : 200
render page , status: status
end
def blocked
end
private
def page
if VALID_ERRORS.include?(params[:id])
params[:id]
else
raise(ActionController::RoutingError.new("/errors/#{params[:id]} not found"))
end
end
def external_error?
EXTERNAL_ERRORS.include?(params[:id])
end
end
最佳答案
在您的代码中,当/errors/500 被调用时,您正在设置状态 200。
def show
# external_error? returns false.
status = external_error? ? 500 : 200
render page , status: status # Status is 200.
end
使用像 pry
或 byebug
这样的调试器来检查状态。你的测试用例没有任何问题。试试这个。
class ErrorsController < ApplicationController
skip_before_filter :authenticate_user!
EXTERNAL_ERRORS = ['sso']
VALID_ERRORS = ['404', '403', '500', 'maintenance'] + EXTERNAL_ERRORS
def show
status = error_500? ? 500 : 200
render page , status: status
end
def blocked
end
private
def page
if VALID_ERRORS.include?(params[:id])
params[:id]
else
raise(ActionController::RoutingError.new("/errors/#{params[:id]} not found"))
end
end
def external_error?
EXTERNAL_ERRORS.include?(params[:id])
end
def error_500?
['500'].include?(params[:id]) || external_error?
end
end
关于ruby-on-rails - 检查500页和404页的测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47789236/