[RUBY] Create multiple instances together from FactoryBot with RSpec using create_list

For example, assume that 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 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 be created in the second argument. (The notes = part can be omitted)

By the way, it is also possible to overwrite 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.

Recommended Posts

Create multiple instances together from FactoryBot with RSpec using create_list
Create related data together with FactoryBot for yourself
[RSpec] Unit test (using gem: factory_bot)