Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 758
Arel Avatar asked Oct 31 '25 10:10

Arel


1 Answers

There might be a way of reassigning the value to a FactoryBot (formerly FactoryGirl) instantiation, but RSpec negates the need:

describe User do
  let(:user) { FactoryBot.create(:user) }

  context 'when admin' do
    let(:user) { FactoryBot.create(:user, admin: true) }

    # ...
  end
end
like image 67
coreyward Avatar answered Nov 03 '25 10:11

coreyward