Backo
Backo

Reputation: 18871

How to state FactoryGirl fixtures for associated model data?

I am using Ruby on Rails 3.0.9, RSpec-rails 2 and FactoryGirl. I would like to generate some Factory associated model data related to accounts for users (in the User class I stated the has_one :account association) so to make possible to do the following in spec files:

let(:user) { Factory(:user) } 

it "should have an account" do
  user.account.should_not be_nil # Note: 'user.account'
end

At this time I have a factories/user.rb file like the following:

FactoryGirl.define do
  factory :user, :class => User do |user|
    user.attribute_1
    user.attribute_2
    ...
  end
end

and a factories/users/account.rb file like the following:

FactoryGirl.define do
  factory :users_account, :class => Users::Account do |account|
    account.attribute_1
    account.attribute_2
    ...
  end
end

What is the correct\common way to state FactoryGirl data in order to handle RoR associated models in spec files?

Upvotes: 1

Views: 765

Answers (1)

Joost Baaij
Joost Baaij

Reputation: 7598

First of all, you don't need the :class => User, since it will be inferred automatically.

FactoryGirl.define do
  factory :user do
    attribute_1      'Some'
    attribute_2      'Text'
  end
end

To use associations in your factory, just include the name directly:

FactoryGirl.define do
  factory :post do
    user
    title    'Hello'
    body     'World'
  end
end

In the example above the user will be associated with the post.

You can also use named factories:

FactoryGirl.define do
  factory :post do
    association :user, :factory => :administrator
    title    'Hello'
    body     'World'
  end
end

The documentation explains it all.

Upvotes: 0

Related Questions