Read more

factory_bot: Re-use partial factory definitions

Henning Koch
June 28, 2016Software engineer at makandra GmbH

Let's say you have two factories that share some attributes and traits:

FactoryBot.define do

  factory :user do
    screen_name 'john'
    email 'foo@bar.de'
    trait :with_profile do
      age 18
      description 'lorem ipsum'
    end
  end
  
  factory :client do
    full_name 'John Doe'
    email 'foo@bar.de'
    trait :with_profile do
      age 18
      description 'lorem ipsum'
    end
  end
  
end
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

You can re-use the shared fields by defining a trait outside the other factory definitions:

FactoryBot.define do

  trait :person do
    email 'foo@bar.de'
    trait :with_profile do
      age 18
      description 'lorem ipsum'
    end
  end
  
  factory :user, traits: [:person] do
    screen_name 'john'
  end
  
  factory :client do
    person
    full_name 'John Doe'
  end
  
end
Posted by Henning Koch to makandra dev (2016-06-28 13:13)