Snowblink
APR 09
24

Factory Girl and has_many :through

If you are using Factory Girl, then you may be wondering how to define the factories for those has_many :through associations you have.

Models

The example models we will use are:

class BeeKeeper < ActiveRecord::Base
  has_many :bees
  has_many :hives, :through => :bees
end

class Hive < ActiveRecord::Base
  has_many :bees
  has_many :bee_keepers, :through => :bees
end

class Bee < ActiveRecord::Base
  belongs_to :bee_keeper
  belongs_to :hive
end

Factories for Testing

So, to test these relationships you would define Factories. Let's start by specifying the belongs_tos

Factory.define :bee do |b|
  b.bee_keeper {|a| a.association(:bee_keeper)}
  b.hive {|a| a.association(:hive)}
end

Factory.define :bee_keeper do |bk|
end

Factory.define :hive do |h|
end

By creating a bee, it should also create a beekeeper and a hive.

We're Done!

Actually, this is all you need to do for has_many :through - when you add hives to bee_keepers, they will automatically create the bees!

context "Bee Keepers" do
  setup do
    @bee_keeper = Factory(:bee_keeper)
    @bee_keeper.hives << Factory(:hive)
    @bee_keeper.hives << Factory(:hive)
  end

  should "have 2 hives" do
    assert_equal 2, @bee_keeper.hives.length
  end

  should "have 2 bees" do
    assert_equal 2, @bee_keeper.bees.length
  end
end

This will create:

  • 1 bee keeper
  • 2 bees
  • 2 hives

Hope this helps some of you.

Tagged As