Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryBot: create the same object multiple times

In one of my RSpec test, I am creating multiple objects from the same factory definition

Eg

FactoryBot.create(:model_1)
FactoryBot.create(:model_1)
FactoryBot.create(:model_1)

Is there a method that factory_bot provides to do this in one line

I know that I can do

3.times {FactoryBot.create(:model_1)}

But I am looking for something that factory_bot provides for creating multiple objects of the same model.

Note: FactoryBot was originally named FactoryGirl

like image 746
usha Avatar asked Aug 26 '13 13:08

usha


2 Answers

You can create a list like this (hence create x objects at once):

FactoryBot.create_list(:model_1, 3)

Documentation lives here.

Note: FactoryBot was originally named FactoryGirl

like image 108
apneadiving Avatar answered Oct 25 '22 20:10

apneadiving


FactoryBot.create_list :factory_name, 2, attribute_name: 'value'

Simple and best way to move.

You can ignore the attribute names if not needed the same, and use sequence instead.

like image 39
Nishutosh Sharma Avatar answered Oct 25 '22 22:10

Nishutosh Sharma