FactoryGirl Self-referencing association error
Asked Answered
I

2

7

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?

Intercalary answered 5/9, 2014 at 11:24 Comment(0)
D
12

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

Dubitation answered 5/9, 2014 at 13:15 Comment(0)
N
6

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)

Nutria answered 21/7, 2015 at 23:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.