Factorybot: Creating in Bulk

Created: 2022-01-07, Last Updated: 2023-02-04

Often I find that I need to create more than one record for my specs. A simple create(:some_factory, name: 'something1') repeated multiple times seems inefficient and wrong.

create_list: The Alternative

There is a way to create a set of records in one go, but the drawback is that the objects will not get different values for their attributes. The immediate reaction is to go update each one individually or to revert to a set of create statements, but create_list does allow you to pass in block. It looks something like this.

object_names = %w(Larry, Curly, Moe, Rafael, Leonardo)
fake_somethings = create_list(:some_factory, 5, user: user) do |object, i|
  object.name = object_names[i]
  object.save
end

This is better, but I feel like it could be better. I'm just not sure how. The drawback with this approach is that the modified objects in the block need to be saved. Factorybot doesn't do this automatically.

Back