Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory Girl: Automatically assigning parent objects

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?

like image 965
Ben Scheirman Avatar asked Mar 02 '10 19:03

Ben Scheirman


1 Answers

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
like image 133
gmile Avatar answered Sep 20 '22 23:09

gmile