Thursday, 8 November 2012

Factory Girl is awesome

When doing specs it's always good to setup factories of common models so you can save up time to write code.

http://arjanvandergaag.nl/blog/factory_girl_tips.html

Get the most out of FactoryGirl

1. Use traits for modular factories

Traits are reusable pieces of attribute definitions that you can mix and match into your factories. Traits are to factories what modules are to classes a much more natural and flexible way of sharing common behaviour.
For example, say you have a Post and a Page object that both have a publication date. You could use inheritance to create various combinations:
FactoryGirl.define do
  factory :post do
    title 'New post'

    factory :draft_post do
      published_at nil
    end

    factory :published_post do
      published_at Date.new(2012, 12, 3)
        end
      end

  factory :page do
    title 'New page'
    
    factory :draft_page do
      published_at nil
    end

    factory :published_page do
      published_at Date.new(2012, 12, 3)
    end
  end
end

FactoryGirl.create :draft_page
FactoryGirl.create :published_post

0 comments:

Post a Comment