Factory_girl与validates_presence_of有__的关系
我有2个型号:
# user.rb class User :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.profile => # @user = Factory.build(:user) => # @user.profile => #
但这不起作用! 它告诉我,我的个人资料模型不正确,因为没有用户! (它在用户之前保存配置文件,因此没有user_id …)
我怎样才能解决这个问题? 尝试了一切…… :(我需要调用Factory.create(:user)…
UPDATE
修复了这个问题 – 现在正在使用:
# user_factory.rb Factory.define :user do |u| u.profile { Factory.build(:profile)} end # user.rb class User :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
你可以做什么(因为用户不需要存在配置文件(没有validation)是做两步建设
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