Search code examples
rubyfactory-bot

FactoryGirl create_list pass in multiple values


If I have this factory:

factory :product, class: Product do
  name        { Faker::Commerce.product_name }
  description { Faker::Lorem.paragraph }
  price       { Faker::Number.number(3) }
end

I can use create_list to create 2 products like this:

FactoryGirl.create_list(:product, 2)

but I want to pass in defaults to both my products, I would suppose something theoretically like this?:

prods = [{:name => "Product 1"},{:name => "Product 2"}]
FactoryGirl.create_list(:product, prods.count, prods)

I have searched for a while and cannot find the answer to this, is it possible using an elegant solution like create_list?

The reason I would like this solution is because :product is one of many child associations to a parent model. I would like a configurable way that I could generate the parent model factory through a single FactoryGirl.create command and pass in all the values I would like for child associations (through the use of FactoryGirl's traits and ignore blocks). I hope that makes sense. I could show a bunch of code here but I believe this provides enough context?


Solution

  • You can generate the list yourself:

    data = [{:name => "Product 1"},{:name => "Product 2"}]
    products = data.map { |p| FactoryGirl.create(:product, p) }
    

    Which should leave you with an array of products.