我对列有一个非空约束。我有一个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
.
取决于控制器是否正在拯救 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