FactoryBot: create the same object multiple times

Ruby on-RailsRspecFactory Bot

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

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.

Solution 3 - Ruby on-Rails

Not sure if this has been updated since the answer was posted, but now you would do the following

FactoryBot.create_list(:model_1, 3)

see Getting Started

Solution 4 - Ruby on-Rails

If you need to do this for a model with validation, I was able to do the following in my test.

10.times do |i|
  create(
    :object,
    property: i
  )
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionushaView Question on Stackoverflow
Solution 1 - Ruby on-RailsapneadivingView Answer on Stackoverflow
Solution 2 - Ruby on-RailsNishutosh SharmaView Answer on Stackoverflow
Solution 3 - Ruby on-RailscromacView Answer on Stackoverflow
Solution 4 - Ruby on-RailsCody ElhardView Answer on Stackoverflow