FactoryGirl 2.1.0 Brings the Heat

FactoryGirl 2.1.0 Brings the Heat

Factory Girl has seen a handful of changes over the past six weeks since we released 2.0.0. Some of the highlights:

Simple association syntax

factory :user do
  name "John doe"
end

factory :post do
  author :factory => :user
end

Traits

trait :male do
  gender "Male"
end

trait :admin do
  admin true
end

factory :user do
  factory :male_user,       :traits => [:male]
  factory :admin,           :traits => [:admin]
  factory :male_admin_user, :traits => [:male, :admin]
end

Transient attributes

factory :user do
  rockstar(true).ignore
  name { "Johnny#{" Rockstar" if rockstar}" }
end

> FactoryGirl.create(:user).name                     # "Johnny Rockstar"
> FactoryGirl.create(:user, :rockstar => false).name # "Johnny"

Change associations to build instead of create

factory :profile do
  sequence(:username) {|n| "user-#{n}" }
end

factory :user do
  profile :method => :build
end

Factory modification

FactoryGirl.define do
  factory :user do
    name "John Doe"
    sequence(:email) {|n| "user-#{n}@example.com" }
  end
end

FactoryGirl.modify do
  factory :user do
    email { "#{name.downcase.underscore}@example.com" }
  end
end

Factory reloading (handy in a console)

FactoryGirl.reload # reloads all factories, sequences, and traits

Apart from these features, we’ve ensured that Factory Girl processes different attributes (static attributes, dynamic attributes) in a reasonable order, verified it works on Rails 3.1.0, upgraded the test suite to use Mocha + Bourne instead of RR (we at Thoughtbot love Mocha), and a handful of other handy bug fixes.

Grab Factory Girl 2.1.0 and make testing easier!

Josh Clayton Developer

Sharpen your programming skills by completing coding exercises that are reviewed by other developers at Upcase today.