I have 2 Models:
# user.rb
class User < ActiveRecord::Base
has_one :profile, :dependent => :destroy
end
# profile.rb
class Profile < ActiveRecord::Base
belongs_to :user
validates_presence_of :user
end
# user_factory.rb
Factory.define :user do |u|
u.login "test"
u.association :profile
end
I want to do this:
@user = Factory(:user)
=> #<User id: 88,....>
@user.profile
=> #<Profile id:123, user_id:88, ......>
@user = Factory.build(:user)
=> #<User id: nil,....>
@user.profile
=> #<Profile id:nil, user_id:nil, ......>
But this doesn't work! It tells me that my profile model isn't correct because there is no user! (it saves the profile before the user, so there is no user_id...)
How can I fix this? Tried everything.. :( And I need to call Factory.create(:user)...
UPDATE:
Fixed it with: This fixes the problem, but then Factory.build(:user) saves the user... Dont know why???
Factory.define :user do |u|
u.login "test"
u.after_build { |a| Factory(:profile, :user => a)}
# u.after_build { |a| Factory.build(:profile, :user => a)}
# raises the validate_presence_of :user - error message again...
end
class User < ActiveRecord::Base
has_one :profile, :dependent => :destroy, :inverse_of => :user
end
This should not save the user, but it does!
@user = Factory.build(:user)
=> #<User id: 88,....>
@user.profile
=> #<Profile id:123, user_id:88, ......>
UPDATE
Fixed this issues - working now with:
# user_factory.rb
Factory.define :user do |u|
u.profile { Factory.build(:profile)}
end
# user.rb
class User < ActiveRecord::Base
has_one :profile, :dependent => :destroy, :inverse_of => :user
end
# profile.rb
class Profile < ActiveRecord::Base
belongs_to :user
validates_presence_of :user
end