Posted 5 months ago. Visible to the public. Linked content.

FactoryBot: Traits for enums

FactoryBot allows to create traits from Enums since version 6.0.0

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

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

is equivalent to

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

Both variants may be used like this:

Copy
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.

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Florian Leinsinger
Last edit:
4 months ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Florian Leinsinger to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more