Search code examples
ruby-on-railsrspecfactory-bot

Change an attribute on a Factory after creation of record


Using FactoryBot, I'm having trouble creating a admin Factory in my specs because every user is assigned a default role of user in a before_create callback. This means that any role I assign a factory will be changed to user when the callback happens.

What I really want to do is something like this:

Inside my spec

admin = FactoryBot.create(:user)
admin.role = 'admin'

The second line, admin.role = 'admin' doesn't do anything. Any ideas?

I'm open to better ways of doing this as well.


Solution

  • Just another way

    # Steal some code from MrYoshiji at first.
    factory :user do
      sequence(:username) { |n| "User ##{n}"}
      role 'user'  
    
      # Then a separate factory inside
      factory :admin do
        role 'admin'
      end
    end
    
    # Use
    FactoryBot.create(:admin)