I am trying to create a has_many: has_many relationship with a 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 is 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 is the factory for the admin role:
FactoryGirl.define do
factory :admin, class: Role do
name 'admin'
end
end
The essence of this question:
trait :admin do
association :user, factory: :admin, strategy: :create
end
I run it like this:
FactoryGirl.create: user ,: admin
But it gives me:
FactoryGirl::AssociationDefinitionError: Self-referencing association 'user' in 'admin'
Why is this? And how can I make this user an administrator? Should I create a user_rolefactory and create this?
source
share