factory_bot: Re-use partial factory definitions

Updated . Posted . Visible to the public.

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

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
Henning Koch
Last edit
Dominik Schöler
Keywords
factory_girl, factorybot, mixin
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2016-06-28 11:13)