Factory_bot: Replacement for Deprecated `initialize_with` Functionality

Created on 27 Apr 2020  路  3Comments  路  Source: thoughtbot/factory_bot

Problem this feature will solve

According to these release notes, the initialize_with { ... } is being deprecated and no replacement has been documented:
https://github.com/thoughtbot/factory_bot/releases/tag/v5.2.0

We currently use FactoryBot to instantiate many non-ActiveRecord objects throughout our test suite. Many of these objects are frozen upon construction, or simply do not expose any attribute writers.

For example, see Dry::Struct:
https://dry-rb.org/gems/dry-struct/1.0/

Given some Dry::Struct object, we may have a factory such that:

factory :some_struct, class: 'SomeStruct' do
  skip_create

  initialize_with { new(attributes) }

  # Attributes...
end

This allows us to construct these objects for use in our test suite, as all attributes need to be passed into the constructor.

Desired solution

A replacement for the existing initialize_with { ... }.

If a replacement has already been implemented, it would be best to have a documented upgrade/refactor path.

Alternatives considered

Retain public access to existing initialize_with { ... } hook.

Another possible solution is some sort of DSL to indicate that attributes should be sent to the constructor, however, this is far more restricted in its usefulness.

feature

Most helpful comment

Oh, sorry about the confusion. Thank you for clarification!

All 3 comments

Thanks for the issue @Mihail-K!

The intention here was only to deprecate the method on the top-level FactoryBot module:

FactoryBot.initialize_with

If you are seeing a deprecation warning for this code:

factory :some_struct, class: 'SomeStruct' do
  skip_create

  initialize_with { new(attributes) }

  # Attributes...
end

then that is a bug and should be fixed.

I added https://github.com/thoughtbot/factory_bot/commit/5ba893831b24515d5328ed65b91f603ac462f83d to clarify what was deprecated. Hopefully that helps.

Oh, sorry about the confusion. Thank you for clarification!

Was this page helpful?
0 / 5 - 0 ratings