x8ovkw
Last Updated: February 25, 2016
·
3.131K
· ducknorris
Bf9a49c89790c65e6685c00a6bd00882

Using FactoryGirl and Faker

I like to use a dynamic factories system and so I'm using Faker.

FactoryGirl.define do
  factory :event do
    left_content Faker::Lorem.sentence
    right_content Faker::Lorem.sentence

    trait :small do
      size 'small'
    end

    trait :medium do
      size 'medium'
    end

    trait :large do
      size 'large'
    end
  end
end

While this might be ok, the output may be unwanted. Both left_content and right_content will be the same.

Faker will produce duplicate content. This is very bad when you have uniqueness validators in place.

Same goes for multiple models, nesting and so on.

The solution for duplicate data is pretty simple:

FactoryGirl.define do
  factory :event do
    left_content { Faker::Lorem.sentence }
    right_content { Faker::Lorem.sentence }

    trait :small do
      size 'small'
    end

    trait :medium do
      size 'medium'
    end

    trait :large do
      size 'large'
    end
  end
end

Just replate static values with blocks and you're golden.

Cheers,
C

Say Thanks
Respond