本文介绍了Factory_girl has_one与validates_presence_of的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个型号:

# 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

我想这样做:

@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, ......>

但这不起作用!它告诉我我的个人资料模型不正确,因为没有用户! (它将配置文件保存在用户之前,因此没有user_id ...)

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...)

我该如何解决?尝试了所有.. :(我需要调用Factory.create(:user)...

How can I fix this? Tried everything.. :(And I need to call Factory.create(:user)...

更新

解决了这个问题-现在可以使用:

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

推荐答案

以这种方式解决()

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

然后

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?

(根据您的评论)为避免保存配置文件,请使用Factory.build仅构建它.

(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

这篇关于Factory_girl has_one与validates_presence_of的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:25