Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails factory_girl create_list builds the same object

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!

like image 267
Mihai Vinaga Avatar asked Mar 20 '23 22:03

Mihai Vinaga


1 Answers

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.

like image 53
user54697 Avatar answered Mar 23 '23 16:03

user54697