I'm just getting into Factory Girl and I am running into a difficulty that I'm sure should be much easier. I just couldn't twist the documentation into a working example.
Assume I have the following models:
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
What I want to do is this:
team = Factory.build(:team_with_players)
and have it build up a bunch of players for me. I tried this:
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
But this fails on the :team=>t
section, because t
isn't really a Team
, it's a Factory::Proxy::Builder
. I have to have a team assigned to a player.
In some cases I want to build up a League
and have it do a similar thing, creating multiple teams with multiple players.
What am I missing?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With