Factory_girl 与 validates_presence_of 有关系

2024-04-21

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

我怎样才能解决这个问题?尝试了一切..:( 我需要调用 Factory.create(:user)...

UPDATE

已修复此问题 - 现在使用:

# 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

就这样修复(正如这篇文章所解释的 https://stackoverflow.com/questions/3634533/factory-girl-with-has-many-relationship-and-a-protected-attribute/3635012#3635012)

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

您还可以做的(因为用户不需要配置文件存在(没有对其进行验证)是进行两步构建

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

and then

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

我想在这种情况下,您甚至只需要一步,在配置文件工厂中创建用户并执行

profile = Factory :profile
@user = profile.user

这似乎是正确的做法,不是吗?

Update

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

Factory.define :user do |u|
  u.login "test"
  u.after_build { |a| Factory(:profile, :user => a)}    
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Factory_girl 与 validates_presence_of 有关系 的相关文章

随机推荐