Tom Doe
Tom Doe

Reputation: 906

FactoryGirl association from inherited factory

I am new to testing in Rails, and am having great difficulty testing my associations. I'd like to simply have factories for confirmed users with various roles that I can create in my specs. I'd like to simply have the ability to user = create(:user_superadmin) or user = create(:user_accountadmin), but am having difficulty doing so.

Below is the error I'm encountering when running my spec:

Failure/Error: user = create(:user_superadmin)

     NoMethodError:
       undefined method `name' for :user_superadmin:Symbol

Please see my code below:

factories/role.rb

FactoryGirl.define do
  factory :role_superadmin, class: Role do
    name 'SuperAdmin'
    description 'Lorem ipsum...'
  end
end

factories/user.rb

FactoryGirl.define do
  factory :user do
    email { Faker::Internet.email }
    password { Faker::Internet.password(8) }
    password_confirmation { password }

    factory :confirmed_user do
      confirmed_at Time.zone.now

      factory :user_superadmin do
        association :role, factory: role_superadmin
      end
    end
  end
end

spec

it 'should be a superadmin user' do
  user = create(:user_superadmin)
  expect(user.super_admin?).to be_truthy
end

Any help is much appreciated.

Upvotes: 0

Views: 122

Answers (1)

Aleksey Chebotarev
Aleksey Chebotarev

Reputation: 26

In your definition of the :user_superadmin, try this association:

association :role, factory: :role_superadmin

Notice that :role_superadmin must be a symbol as well so FactoryGirl can find the proper factory.

Upvotes: 1

Related Questions