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?
It probably doesn't like that you have both a user's trait called :admin
and a factory called admin
for a different class.
Try renaming your role factory for :admin_role
to see if it's still the problem
Search for "self-referencing" in the FactoryGirl's source file here. This error happened because you were defining "association_with_same_name"
You'll need to rename the trait or factory to a different name (e.g. trait :admin_user)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With