I'm trying to create a has_many:has_many relationship with factory girl.
Here are my models:
class User < ActiveRecord::Base
has_many :user_roles
has_many :roles, through: :user_roles
end
class UserRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
class Role < ActiveRecord::Base
has_many :user_roles
has_many :users, through: :user_roles
end
Here's the factory for my user:
FactoryGirl.define do
factory :user do
user_name { Faker::Name.user_name }
trait :admin do
association :user, factory: :admin, strategy: :create
end
end
end
Here's the factory for an admin role:
FactoryGirl.define do
factory :admin, class: Role do
name 'admin'
end
end
The crux of this question is:
trait :admin do
association :user, factory: :admin, strategy: :create
end
I trigger it like this:
FactoryGirl.create :user, :admin
But that gives me:
FactoryGirl::AssociationDefinitionError: Self-referencing association 'user' in 'admin'
Why is this? And how should I make this user an admin? Should I create a user_role
factory and create that?