【问题标题】:Factory_girl has_one relation with validates_presence_ofFactory_girl has_one 与 validates_presence_of 的关系
【发布时间】:2010-09-06 02:26:49
【问题描述】:

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

更新

修复了这个问题 - 现在正在使用:

# 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.build(:profile, :user =>a) 来“构建”配置文件?
  • 是的,试过了,但没用...我上面的“丑陋”解决方案现在可以用了...感谢您的帮助!

标签: ruby-on-rails testing ruby-on-rails-3 ruby-on-rails-plugins factory-bot


【解决方案1】:

这样解决 (as explained in this post)

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

您也可以做的(因为用户不需要存在个人资料(没有对其进行验证))是进行两步构建

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

然后

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

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

profile = Factory :profile
@user = profile.user

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

更新

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

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

【讨论】:

  • 我之前尝试过,但没有成功,因为配置文件在用户之前保存...所以 validates_presence_of :user-validation 不会接受保存...用我的修复它上面的解决方案!
  • 好的,没看到您回复了自己的帖子。反正这很奇怪。我们经常使用工厂女孩(我工作的地方),我从未见过这个问题。
  • 好的...但是我的解决方案最终没有成功..即使我调用 Factoy.build(:user),用户也会被保存...不知道为什么... aaarghh 更新了我的帖子...
  • 我很困惑...所有都适用于“u.profile { Factory.build(:profile)} ”,但不适用于您的建议“u.profile { |p| p.association( :profile) }"... 疯了^^
  • 当您将答案更改为我上面的修复时,我会将您的答案标记为已接受...谢谢!
猜你喜欢
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多