Backo
Backo

Reputation: 18881

How to properly use factories having multiple associations to the same model?

I am using Ruby on Rails 3.2.2, FactoryGirl 3.1.0 and FactoryGirlRails 3.1.0. I have a model that has two association to another model:

class Article < ActiveRecord::Base
  belongs_to a_users, :class_name  => 'User'
  belongs_to b_users, :class_name  => 'User'
end

In my factory file I have:

factory :article, :class => Article do
  title "Sample title"

  association :a_users, factory: :user
  association :b_users, factory: :user
end

By using the above code it will create two users, but I would like that both associations have the same user (without to create multiple users). How can I make that?

Upvotes: 2

Views: 305

Answers (1)

Alan Gandarilla
Alan Gandarilla

Reputation: 31

Perhaps this isn't the most elegant solution or the one you were looking for, but what I would do is in your tests, use your factories to create an article and a user, then stub both a_user and b_user with the user you created.

Upvotes: 2

Related Questions