Read more

FactoryBot: Traits for enums

Florian Leinsinger
July 10, 2020Software engineer at makandra GmbH

FactoryBot allows to create traits from Enums since version 6.0.0 Show archive.org snapshot

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

The automatic definition of traits for Active Record enum attributes is enabled by default, for non-Active Record enums you can use the traits_for_enum method.

Example

factory :user do
  traits_for_enum :role, %w[admin contact] # you can use User::ROLES here, of course
end

is equivalent to

factory :user do
  trait :admin do
    role { 'admin' }
  end

  trait :contact do
    role { 'contact' }
  end
end

Both variants may be used like this:

create(:user, :admin)
create(:user, :contact)

So you can easily add new roles to a user model and start testing without adding new traits by yourself.

Note: If you not provide a second argument to traits_for_enum, FactoryBot will attempt to get the values by calling the pluralized attribute_name class method, which would be User.roles in this example.

Posted by Florian Leinsinger to makandra dev (2020-07-10 14:28)