Reputation: 3794
When i don't use factory_girl
I can create objects in my rspec test as
u = User.create(email: '[email protected]', 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
This way i can check for validation error i.e
expect(u.errors[:role]).to_not be_empty
but if i use factory girl
factory :user_no_role, class: User do
email '[email protected]'
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
I get the following error
User role should be present
Failure/Error: u = create(:user_no_role)
ActiveRecord::RecordInvalid:
Validation failed: Role can't be blank
does factory_girl create method throw error? if so how can i test for validation error with rspecs as done above? Thanks!
Upvotes: 0
Views: 396
Reputation: 3407
Create will throw validation exceptions, since you are trying to save them immediately.
If you would just build one, like:
u = User.new(...)
u.valid?
=> false
u.errors # is not empty
This should apply to FactoryGirl.build
too
it 'role should be present' do
u = build(:user_no_role)
expect(u.errors[:role]).to_not be_empty
end
BTW: User.create
will not throw exceptions - but User.create!
does.
See the ActiveRecord docs of create! and FactoryGirl docs of build for more infos.
Upvotes: 1