【问题标题】:Test cases for checking page 500 & 404检查页面 500 和 404 的测试用例
【发布时间】:2017-12-13 09:09:55
【问题描述】:

我正在尝试通过第 404 页和第 500 页的测试用例。但是我遇到了很多问题

1) 首先,我在 app/views/errors/ 中有一个页面 500.html.erb,它没有被调用。
2) 如果我运行以下测试我的系统冻结,我需要重新启动我的系统
3) 如果我评论这一行 expect{get "/errors/foo"}.to raise_exception(ActionController::RoutingError)。所以在我的控制器动作名称 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

【问题讨论】:

  • 这是一个仅供测试的问题,即当您在浏览器中打开 URL 时它是否有效?
  • 当我尝试从浏览器点击时它工作正常
  • 您能否在不冻结系统的情况下打开测试中的任何其他 URL,即问题是否特定于 ErrorsController?
  • 是的,我可以在 errors_controller 中打开除 404 和 500 之外的其他 URL
  • @Stefan - 你知道我哪里做错了吗?

标签: ruby-on-rails ruby ruby-on-rails-4 rspec rspec3


【解决方案1】:

在您的代码中,当调用 /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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-07
    • 2012-02-29
    • 2013-10-21
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2013-08-03
    相关资源
    最近更新 更多