Traits in Factory Girl
FactoryGirl’s traits are an outstanding way to DRY
up your tests and factories.
Traits
Traits allow you to group attributes, callbacks, and associations in one concise area together and then apply them to any factory. Traits specify the states/types of factories.
factory :user do
name { Faker::Name.name }
admin false
trait :admin do
admin true
end
trait :with_profile_photo do
photo_url { Faker::Avatar.image }
end
end
create(:user).admin?
#=> false
create(:user, :admin).admin?
#=> true
We can now define new factory admin_with_profile_photo
with combination of above 2 traits, which will create new admin user with profile photo. This is a good way to DRY
up factories by reusing traits.
factory :admin_with_profile_photo, traits: [:admin, :with_profile_photo], parent: :user