FactoryGirl owns_and association and validates_presence_of failing - foreign key is associated, object is not
After upgrading from FactoryGirl 2.5.2 to 4.5.0, belongs_to
no association checks are performed.
Two model files:
class User < ActiveRecord::Base
...
has_many :things
...
end
class Thing < ActiveRecord::Base
...
belongs_to :user
validates_presence_of :user
...
end
factory:
FactoryGirl.define
factory :thing do
association :user
...
end
end
Making a new one thing
always fails when speaking User must be provided
. When I step into the code, the problem is that the foreign key is set correctly, but the associated object appears to be zero.
>> user = create(:user)
( returns saved "user" object )
>> user.id
1
>> thing = build(:thing, user: user)
( returns new "thing" object )
>> thing.valid?
false
>> thing.user_id
1
>> User.find(1).present?
true
>> thing.user
nil
I've tried all kinds of combinations and variations. I tried using blocks after(:build)
to set the user and use a different FactoryGirl syntax. I've tried using just user
instead of association. But it always boils down to this problem - there is an associated key and it is a valid one, but not a related object (although that object exists and persists).
Environment:
ruby 2.1.5
factory_girl 4.5.0
factory_girl_rails 4.5.0
rails 4.2.0
rspec 3.1.0
source to share