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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)