Reputation: 198
I'm working on a model test which looks like this:
require 'rails_helper'
RSpec.describe Demand, type: :model do
it 'has a valid factory' do
expect(create(:demand)).to be_valid
end
it 'is invalid without a parent_id' do
expect(create(:demand, parent_id: nil)).to_not be_valid
end
end
now the second test "is invalid without a parent_id" fails with this message:
Demand is invalid without a parent_id
Failure/Error: expect(create(:demand, parent_id: nil)).to_not be_valid
ActiveRecord::RecordInvalid:
Validation failed: Parent can't be blank
This feels weird because the record tells me that it can't be blank - that's exactly what I'm testing, isn't it? Any suggestions?
EDIT: I found the mistake. Check out the answer below.
Upvotes: 2
Views: 19
Reputation: 198
In case someone makes the same mistake, here's the answer:
it 'is invalid without a parent_id' do
expect(build(:demand, parent_id: nil)).to_not be_valid
end
It needs to be "build" instead of "create".
Upvotes: 3