Skip to content
KevinTriplett edited this page Apr 8, 2012 · 14 revisions

You can add factories to any of the following places:

  1. test/factories.rb (Test::Unit)
  2. spec/factories.rb (RSpec)
  3. Under a test/factories/
  4. Or spec/factories/

A typical factory file looks like this:

FactoryGirl.define do
  factory :user do
    first_name 'John'
    last_name  'Doe'
    age        { 1 + rand(100) }
  end

  factory :admin, :parent => :user do
    admin true
  end
end

Make sure to add this to your RSpec configure block:

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end

Make sure to add this for Test::Unit:

class ActiveSupport::TestCase
  include FactoryGirl::Syntax::Methods
end

Make sure to add this for Cucumber:

World Factory::Syntax::Methods

Once your factories are defined, you can use them in the following ways:

# Saved instance
user = create(:user)

# Unsaved instance
user = build(:user)

# Attribute hash (ignores associations)
user_attributes = attributes_for(:user)

# Stubbed object
user_stub = build_stubbed(:user)

# Override attributes
user = create(:user, first_name: 'Joe')

Definition sequencing and associations If you need uniqueness on a field, sequencing comes in handy. The sequences can then be used in your other definitions

FactoryGirl.define do
  sequence :email do |n|
    "email#{n}@factory.com"
  end

  factory :user do
    email
    password "foobar"
    password_confirmation "foobar"
  end
end

Or you can use the generated above email sequence in any place of your code:

new_email = FactoryGirl.generate(:email)

Sequencing can also be defined within the factory definition.

FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "email#{n}@factory.com" }
    password "foobar"
    password_confirmation "foobar"
  end
end

For completeness’ sake, we can make password_confirmation match the password by using a block to define its value.

FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "email#{n}@factory.com" }
    password "foobar"
    password_confirmation {|u| u.password }
  end
end

The sequencing also works for associations. The code below will create a new user with the sequenced email from above.

FactoryGirl.define do
  factory :post do
    name "Post name"
    user
  end
end