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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)