我刚刚进入工厂女孩和我遇到困难,我敢肯定要容易得多。我不能文档捻成的工作示例。

假设我有以下型号:

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

我想要做的是这样的:

team = Factory.build(:team_with_players)

和有它建立了一堆的球员对我来说。我试图这样:

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

但这个失败的:team=>t部分,因为t是不是一个真正的Team,这是一个Factory::Proxy::Builder。我的的有分配给玩家一个团队。

在某些情况下,我想建立一个League并将它做类似的事情,创建多个组与多个玩家。

我缺少什么?

有帮助吗?

解决方案

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

其他提示

这样如何:

Factory.define :team_with_players, :class => :team do |t|
  t.sequence { |n| "team-#{n}" }
  t.players do |team| 
    25.times.collect { |n| team.association(:player) }
  end
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top