Question

I have the following factory:

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

When I call FactoryGirl.create_list(:product, 3) it inserts in the database the same product with only a different id. I would like to have a different name, description and price for each of the products.

Do you guys know a solution to this problem? Thanks!

Was it helpful?

Solution

name, description, and price are being treated as static attributes; this means the value is calculated once (when the factories are loaded) and will never change (and the reason why the data is the same for each instance of Product.

Instead, wrap the values in a block:

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

Every time the factory is run, this block gets executed - and in the case of Faker, that means it'll generate a new value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top