ruby-on-rails - 检查500页和404页的测试用例

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

我正在尝试通过第 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

使用像 prybyebug 这样的调试器来检查状态。你的测试用例没有任何问题。试试这个。

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/

相关文章:

ruby-on-rails - 安装 ruby​​ rvm 时出错

ruby - 如何检测元素是否存在于 Watir 中

sql - Rails 4 中的 sanitize_sql_array

ruby-on-rails - rails : Formtastic: Select-Boxes without primary blank field

javascript - 如何将错误消息关联到 json 响应中的 'error' 键

ruby-on-rails - 从 Rails 3 中的 JSON 响应中获取数据

MYSQL错误time.now

ruby - 如何在 ruby​​ 测试中正确使用正则表达式

javascript - Rails - 使链接与 ajax 一起工作

ruby-on-rails - 在 Ruby on Rails 中的多对多关系中,如何使用父表表单中的数据在连接表中创建记录?