FactoryBot to build list of objects with trait

Gandalf StormCrow picture Gandalf StormCrow · Jan 17, 2014 · Viewed 13.5k times · Source

I'm using factory_bot to create objects in my test, here is a example of my factory:

factory :user do
  name "John"
  surname "Doe"

  trait :with_photo do
    ignore do
      photo_count 1
    end

    after(:create) do |user, evaluator|
      FactoryBot.create_list(:photo, evaluator.photo_count)
    end
  end
end

So I can create a user with photo like:

FactoryBot.create(:user, :with_photo)

Or without photo :

FactoryBot.create(:user) 

Or create a list of users :

FactoryBot.build_list(:user, 5)

But how can I build a list of users with trait (trait being :with_photo), if I wanted to create five of them with photo?

Note: FactoryBot was previously called FactoryGirl

Answer

Thilo picture Thilo · Jan 17, 2014

Doesn't this work? It should...

FactoryBot.build_list(:user, 5, :with_photo)

Reference

FactoryBot - Building or Creating Multiple Records

Note: FactoryBot was previously called FactoryGirl