Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryBot to build list of objects with trait

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

like image 561
Gandalf StormCrow Avatar asked Jan 17 '14 14:01

Gandalf StormCrow


People also ask

What is FactoryBot Ruby?

Factory Bot, originally known as Factory Girl, is a software library for the Ruby programming language that provides factory methods to create test fixtures for automated software testing.

What is trait in FactoryBot?

FactoryBot's traits are an outstanding way to DRY up your tests and factories by naming groups of attributes, callbacks, and associations in one concise area. Imagine defining factories but without the attributes backed by a specific object.


2 Answers

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

like image 102
Thilo Avatar answered Oct 31 '22 01:10

Thilo


You can also pass multiple traits to create_list and build_list example;

factory :user do   name { "Friendly User" }    trait :male do     name { "John Doe" }     gender { "Male" }   end    trait :admin do     admin { true }   end end  # creates 3 admin users with gender "Male" and name "Jon Snow" using the admin and male trait build_list(:user, 3, :admin, :male, name: "Jon Snow") create_list(:user, 3, :admin, :male, name: "Jon Snow") 

Just make sure the traits comes after the number of records you wish to create, the last argument is a hash that would override the record attribute.

More on traits on the official docs

like image 35
theterminalguy Avatar answered Oct 31 '22 00:10

theterminalguy