Factory Girl:自动分配父对象

Ben*_*man 9 ruby unit-testing ruby-on-rails factory-bot

我刚刚进入工厂女孩,我遇到了一个困难,我肯定应该更容易.我只是无法将文档扭曲成一个有效的例子.

假设我有以下型号:

class League < ActiveRecord::Base
   has_many :teams
end

class Team < ActiveRecord::Base
   belongs_to :league
   has_many :players
end

class Player < ActiveRecord::Base
   belongs_to :team
end
Run Code Online (Sandbox Code Playgroud)

我想要做的是:

team = Factory.build(:team_with_players)
Run Code Online (Sandbox Code Playgroud)

让它为我建立一堆球员.我试过这个:

Factory.define :team_with_players, :class => :team do |t|
   t.sequence {|n| "team-#{n}" }
   t.players {|p| 
       25.times {Factory.build(:player, :team => t)}
   }
end
Run Code Online (Sandbox Code Playgroud)

但这:team=>t部分失败了,因为t它不是真的Team,它是一个Factory::Proxy::Builder.我必须将一个团队分配给一名球员.

在某些情况下,我想建立一个League并让它做类似的事情,创建多个拥有多个玩家的团队.

我错过了什么?

gmi*_*ile 5

Factory.define :team do |team|
  team.sequence(:caption) {|n| "Team #{n}" }
end

Factory.define :player do |player|
  player.sequence(:name) {|n| "John Doe #{n}" }
  player.team = nil
end

Factory.define :team_with_players, :parent => :team do |team|
  team.after_create { |t| 25.times { Factory.build(:player, :team => t) } }
end
Run Code Online (Sandbox Code Playgroud)