Factory_girl has_one relation with validates_presence_of

好久不见. 提交于 2019-12-22 04:16:07

问题


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 this issue - 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

回答1:


Fix it that way (as explained in this post)

Factory.define :user do |u|
  u.login "test"
  u.profile { |p| p.association(:profile) }
end

What you can do as well (as a user don't need a profile to exist (there's no validation on it) is to do a two steps construction

Factory.define :user do |u|
  u.login "test"
end

and then

profile = Factory :profile
user = Factory :user, :profile => profile

I guess in that case you even just need one step, create the user in the profile factory and do

profile = Factory :profile
@user = profile.user

That seems the right way to do it, isn't it?

Update

(according to your comment) To avoid saving the profile use Factory.build to only build it.

Factory.define :user do |u|
  u.login "test"
  u.after_build { |a| Factory(:profile, :user => a)}    
end


来源:https://stackoverflow.com/questions/3648699/factory-girl-has-one-relation-with-validates-presence-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!