【发布时间】:2016-10-21 12:30:05
【问题描述】:
我在测试失败时遇到了这个问题,因为验证存在:true 不起作用。我想知道为什么它没有触发。所以,这是我拥有的代码:
控制器中的简单更新
def update
person = Person.find_by( params[:id] )
if person.update( params_person )
render json: {}, status: :ok
else
render json: person.errors, status: :422
end
end
def params_person
params.require( :person ).permit( :firstname, :lastname, ... , hobbies: [] )
end
hobbies: [] 是一个字符串数组,例如 ['playing dota', 'basketball', 'coding', ... ]
人物模型
class Person < ActiveRecord::Base
...
validates :hobbies, presence: true
...
end
如果我做了一个请求
{ ...
...
hobbies: nil/'',
...
...
}
验证仍然通过,没有更新爱好作为数据nil/''
更新
describe '#update' do
let( :user ) { create( :user ) }
fcontext 'when params missing' do
before do
put :update, id: person.id,
person: {
....,
....,
hobbies: nil
}
end
it 'respond an error message' do
expect( response_body ).to include( "Hobbies can't be blank" )
end
it { expect( response ).to have_http_status( 422 ) }
end
【问题讨论】:
-
你能发布你的测试吗?
-
@CdotStrifeVII 帖子已更新 .. 谢谢!
-
您在测试中发送用户 {},但控制器使用人员。
-
对不起。我修改它应该是人@eagleeye。
标签: ruby-on-rails ruby validation strong-parameters