我正在使用factory_girl_rails而不是灯具。这是我的模特:
class User < ActiveRecord::Base
has_many :tasks
end
class Task < ActiveRecord::Base
belongs_to :user
end
这是我的工厂:
Factory.define :user do |u|
end
Factory.define :task do |t|
t.association :user, :factory => :user
end
在测试中我这样做:
user = Factory.create :user
(1..5).each { Factory.create(:task, :user => user)}
我遇到的问题是,之后user.tasks
只包含一项任务。
我尝试过像这样定义user
工厂:
Factory.define :user do |u|
u.tasks {|tasks| [tasks.association(:user)] }
end
并且像这样:
Factory.define :user do |u|
u.tasks {|tasks| [tasks.association(:user), tasks.association(:user)] }
end
在这两种情况下Factory.create(:user)
都会导致无限循环。
答案 0 :(得分:3)
我认为你所做的是倒退 - 你可以从用户创建任务,但不会像你想要的那样反过来。从概念上讲,关联从用户到任务。
我所做的是为该类型的用户创建一个特殊的工厂。
Factory.define :user_with_tasks, :parent => :user do |user|
user.after_create {|u| 5.times { Factory.create(:task, :user => user) } }
end
此外,如果您只想使用默认工厂,则只需执行此操作
Factory.define :task do |f|
f.user :user
end
无需指定工厂
更新:看起来其他人过去做过类似的事情: Populating an association with children in factory_girl
答案 1 :(得分:0)
啊,这有效:
Factory.define :task do |t|
t.association :user
t.after_create {|t| t.user.tasks << t}
end
John,你的方法可行但我实际上无法使用你描述的内容,因为在我的测试中,任务还需要引用另一个(未提及的)模型,我没有看到在{{1中引用它的方法工厂定义。