FactoryBot: create the same object multiple times
Asked Answered
S

4

76

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

Spondee answered 26/8, 2013 at 13:52 Comment(0)
F
141

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

Fatigue answered 26/8, 2013 at 13:54 Comment(2)
What if i want to create multiple objects like FactoryGirl.create(:model_1, :type => "something")?Spondee
look in the doc, you can pass params hash as third argumentFatigue
L
15
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.

Loughlin answered 14/9, 2016 at 11:40 Comment(0)
M
8

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

Mansuetude answered 24/7, 2015 at 7:28 Comment(0)
N
4

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
Nosography answered 1/1, 2019 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.