Today I Learned

hashrocket A Hashrocket project

FactoryBot Traits inside Traits

Today I learned you can nest FactoryBot traits within other traits. Traitception?!

Say you have a blog post model with a deleted_at attribute, and an optional deleted_by attribute. You could have:

FactoryBot.define do
  factory :post do
    trait :deleted do
      deleted_at { Time.current }
    end

    trait :deleted_by_admin do
      deleted
      deleted_by { :admin }
    end
  end
end

There the deleted in deleted_by_admin references the deleted trait above it.

You could alternatively define a new factory that composes the two traits, but it's always nice to have options.

factory :admin_deleted_post, traits: [:deleted, :deleted_by_admin]
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.