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?
First of all, you don’t need the :class => User, since it will be inferred automatically.
To use associations in your factory, just include the name directly:
In the example above the user will be associated with the post.
You can also use named factories:
The documentation explains it all.