Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryGirl Self-referencing association error

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?

like image 784
Starkers Avatar asked Sep 05 '14 11:09

Starkers


2 Answers

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

like image 77
Marc-Alexandre Bérubé Avatar answered Oct 21 '22 01:10

Marc-Alexandre Bérubé


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)

like image 41
konyak Avatar answered Oct 20 '22 23:10

konyak