Factory-girl create that bypasses my model validation
This isn't very specific to FactoryGirl, but you can always bypass validations when saving models via save(validate: false)
:
describe ".current" do
let!(:current_group) { FactoryGirl.create(:group) }
let!(:old_group) do
g = FactoryGirl.build(:group, expiry: Time.now - 3.days)
g.save(validate: false)
g
end
specify { Group.current.should == [current_group] }
end
I prefer this solution from https://github.com/thoughtbot/factory_girl/issues/578.
Inside the factory:
trait :without_validations do
to_create { |instance| instance.save(validate: false) }
end
It's a bad idea to skip validations by default in factory. Some hair will be pulled out finding that.
The nicest way, I think:
trait :skip_validate do
to_create {|instance| instance.save(validate: false)}
end
Then in your test:
create(:group, :skip_validate, expiry: Time.now + 1.week)
foo = build(:foo).tap { |u| u.save(validate: false) }
For this specific date-baesd validation case, you could also use the timecop gem to temporarily alter time to simulate the old record being created in the past.