Factory Girl: Automatically assigning parent objects

Posted by Ben Scheirman on Stack Overflow See other posts from Stack Overflow or by Ben Scheirman
Published on 2010-03-02T19:59:21Z Indexed on 2010/03/16 23:31 UTC
Read the original article Hit count: 353

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?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about ruby-on-rails