【问题标题】:How to test that a request does not return 500 error?如何测试请求不返回 500 错误?
【发布时间】:2017-03-17 23:16:05
【问题描述】:

我正在尝试创建一个 RSpec 测试来检测请求是否会使控制器崩溃,通常是 500 错误。所以我希望能够区分:

 nil.invalid_method # raises NoMethodError

来自

 params.require(:required_parameter) # raises ActionController::ParameterMissing

以通用方式在控制器中。当我进行requestfeaturecontroller 测试时,它会引发异常:

describe "Post", type: :request do
  it 'does not crash when no params given' do
    post '/posts' # this line launches an exception
    expect(page).to_not have_http_status(500)
  end
end

似乎在 RSpec(或我不知道的 Rails)之前有不同的行为,类似于我正在寻找的:

我该怎么做?或者你会怎么做?

感谢您的宝贵时间。

【问题讨论】:

  • @max @spickermann 我没有正确解释自己。我的意思不是检查引发了哪个异常。也许我的控制器正在以另一种方式处理问题,即:它在 html 中返回一条错误消息。因此,我想要一种通用方式 来检测不存在“编码错误”。 Rails 使用异常来处理几种情况,这些情况是正确的代码,例如ActionController::ParameterMissing,因为我不能使用except { ... }.to_not raise_exception

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


【解决方案1】:

您可以使用不呈现 500 但引发异常的控制器规范:

describe "PostController", type: :controller do
  describe "POST index" do
    it 'does not crash with valid params' do
      expect {
        post :index, { post: { title: 'foo' } }
      }.to_not raise_exception 
    end
  end

  describe "POST index" do
    it 'crashes without params' do
      expect {
        post :index
      }.to raise_exception(ActionController::ParameterMissing)
    end
  end
end

还要注意expect 后面的大括号{ ... }

【讨论】:

    【解决方案2】:

    您可以使用raise_error 匹配器来测试控制器不会引发未捕获的异常:

    RSpec.describe "Things", type: :request do
      describe "POST /things" do
        it "does not raise an error" do
          # we pass a block to expect
          expect { post things_path }.to_not raise_error
        end
      end
    end
    

    如果使用rescue 关键字或Rails rescue_from 在控制器中挽救了异常,您将照常测试响应代码:

    class ThingsController < ApplicationController
      rescue_from ActionController::ParameterMissing do
        head 500
      end
    
      def create
        raise ActionController::ParameterMissing.new('foo')
      end
    end
    
    RSpec.describe "Things", type: :request do
      describe "POST /things" do
        it "work even if the param is not provided" do
          post things_path
          expect(response).to successful
        end
      end
    end
    

    在这种情况下,测试响应是否符合您的预期更为有用 - 而不是它不是 500。

    【讨论】:

      猜你喜欢
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 2017-12-13
      • 1970-01-01
      • 2020-08-03
      • 2020-04-21
      • 2021-04-24
      相关资源
      最近更新 更多