FactoryBot allows to create traits from Enums since version 6.0.0 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 12:28)