views:

309

answers:

2

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?

+1  A: 

How about this:

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
Priit
But if the player needs a reference to the team, where do I get that? In this example, "team" refers to a factory object...
Ben Scheirman
I have something similar to this: team.association(:player, :team_id => team) seems strange but works for me.
Priit
when I do that it complains: "Expected Team, but was FactoryGirl::Proxy" or something like that.
Ben Scheirman
A: 
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
gmile