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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)