Factorybot: Traits

Created: 2020-02-04, Last Updated: 2023-02-04

This was written based on factory_bot 5.1.0. There might be differences that you'll need to account for in your version.

Traits are a convenient way to create specific factories in that they allow you to extend existing factories by tweaking specific attributes or relationships. This means that you can create a generic factory for an object and then use traits to create specific factories. For example, I can create a user factory like this

  factory :user do email { Faker::Internet.email }
    password { "password"}
    password_confirmation { "password" }
  end

Then add a trait to set the is_admin attribute.

  factory :user do
    email { Faker::Internet.email }
    password { "password"}
    password_confirmation { "password" }

    trait :admin do
      is_admin { true }
    end
  end
Back