当我不使用factory_girl时
我可以在我的rspec测试中创建对象
u = User.create(email: 'as@wewe.com', password: 'asdqweqweqe', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w')
expect(u.errors[:email]).to_not be_empty
expect(u.errors[:role]).to_not be_empty
这样我可以检查验证错误,即
expect(u.errors[:role]).to_not be_empty
但如果我使用工厂女孩
factory :user_no_role, class: User do
email 'asd@we.com'
password 'asasdasdasd'
admin true
firstname 'qwe'
lastname 'wer'
grade 5
section 'w'
end
it 'role should be present' do
u = create(:user_no_role)
expect(u.errors[:role]).to_not be_empty
end
我收到以下错误
User role should be present
Failure/Error: u = create(:user_no_role)
ActiveRecord::RecordInvalid:
Validation failed: Role can't be blank
factory_girl创建方法抛出错误?如果是这样,我如何测试rspecs的验证错误,如上所述?谢谢!
答案 0 :(得分:1)
Create会抛出验证异常,因为您试图立即保存它们。
如果您只想构建一个,例如:
u = User.new(...)
u.valid?
=> false
u.errors # is not empty
这也适用于FactoryGirl.build
it 'role should be present' do
u = build(:user_no_role)
expect(u.errors[:role]).to_not be_empty
end
BTW:User.create
不会抛出异常 - 但User.create!
会抛出异常。
有关更多信息,请参阅ActiveRecord docs of create!和FactoryGirl docs of build。