[Ruby] Create multiple instances from FactoryBot in batch with RSpec using create_list

less than 1 minute read


When writing an RSpec test, write down a convenient method create_list that can create multiple instances together.


For example, suppose the factory of note is defined as follows.

factory/notes.rb


FactoryBot.define do
  factory :note do
    title {'sample-note'}
    description {'sample-description'}
  end
end

When you want to create 5 note instances in the test, it is troublesome to create them one by one as shown below.

spec/system/xxx_spec.rb


RSpec.describe'yyyy' do
  let(:note1) {create(:note)}
  let(:note2) {create(:note)}
  let(:note3) {create(:note)}
  let(:note4) {create(:note)}
  let(:note5) {create(:note)}
  ...
end

If you use create_list here, you can create note instances all at once.

spec/system/xxx_spec.rb


RSpec.describe'yyyy' do
  notes = create_list(:note, 5)
  ...
end

Specify the original factory in the first argument and the number to create in the second argument. (You can omit the notes = part)

By the way, it is also possible to create by overwriting some of the attributes.

spec/system/xxx_spec.rb


RSpec.describe'yyyy' do
  notes = create_list(:note, 5, title:'Hello, World')
  ...
end

that’s all.

Tags: ,

Updated: