Jamie's Blog

Lessons from a life of startups, coding, countryside, and kids

Creating association collections in FactoryGirl

I’m still discovering the joys of using FactoryGirl to create test data but I particularly like this pattern for creating a collection of associated objects.

FactoryGirl.define do
  factory :list do
    name "My List"
  end

  trait :with_items do
    ignore do 
      item_count 3
    end

    after(:create) do |plan, evaluator|
      FactoryGirl.create_list(:item, evaluator.item_count, list: list)
    end
  end
end

Now, I can call

FactoryGirl.create :list

to create an empty list,

FactoryGirl.create :list, :with_items

to create a list with 3 items or I can even specify the number of items using

FactoryGirl.create :list, :with_items, :item_count 50

I’m also fond of naming my traits :with_xxxx as it reads well like in the examples above