Read more

How to change the class in FactoryBot traits

Arne Hartherz
September 01, 2017Software engineer at makandra GmbH

FactoryBot allows a :class option to its factory definitions, to set the class to construct. However, this option is not supported for traits.

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

Most often, you can just define a nested factory instead of a trait, and use the :class option there.

factory :message do
  factory :reply, class: Message::Reply do
    # ...
  end
end

If you need/want to use traits instead (for example, it might make more sense semantically), you can not use a :class on a trait.

In that case, use initialize_with to define the record's construction.

factory :message do
  trait :reply do
    initialize_with { Message::Reply.new(attributes) }
    # ...
  end
end

Now FactoryBot.build(:message, :reply) will construct a Message::Reply instead of a Message.

Posted by Arne Hartherz to makandra dev (2017-09-01 08:39)