用于nil的未定义方法`response_code':IntegrationTest的NilClass失败

时间:2018-01-27 14:44:54

标签: ruby-on-rails ruby integration-testing ruby-on-rails-5.1

我对列有一个非空约束。我有一个IntegrationTest测试用例post是没有该列的实例。 我的目标是声明返回的响应代码为400。

我的第一次尝试是:

test "should fail if no context" do
  post trips_url, params: { trip: { state: @trip.state } }
  assert_response 400
end

但是Minitest::UnexpectedError: ActiveRecord::NotNullViolation: SQLite3::ConstraintException: NOT NULL constraint failed: trips.context:...失败了。

我真的不明白。不是post类似于HTTP客户端,所以它不应该受到控制器中抛出的异常的影响吗?

但无论如何,接下来我试过了:

test "should fail if no context" do
  assert_raises(ActiveRecord::NotNullViolation) do
    post trips_url, params: { trip: { state: @trip.state } }
  end
  assert_response 400
end

但是Minitest::UnexpectedError: NoMethodError: undefined method `response_code' for nil:NilClass失败,好像因为抛出异常而没有设置response_code

所以,我的问题:如何实现我的目标?在测试端点时,我并不关心抛出的异常;我关心它的回复是什么。那么,如何在失败的情况下断言响应?

我正在使用Rails 5.1.4

1 个答案:

答案 0 :(得分:1)

取决于您的控制器是否正在抢救ActiveRecord :: NotNullViolation并渲染400?我想控制器和规格就像下面的

控制器代码

class User < ApplicationController
   def create
    .....
   rescue ActiveRecord::NotNullViolation => e
    render text: e.message, status: :bad_request 
  end
end

规范代码

it 'POST with null data returns bad request' do
  post to/user/path
  expect(response.code).to eq '400'
end