Updating from FactoryGirl to factoryBot results in NoMethodError
Asked Answered
P

1

6

I tried to convert from FactoryGirl to FactoryBot. This should not be a big issue but i do not get it to work. The code:

Added to Gem File

gem 'factory_bot'

Added to spec_helper

FactoryBot.definition_file_paths = %w(spec/factories)
FactoryBot.find_definitions

config.include FactoryBot::Syntax::Methods

Factory

FactoryBot.define do
  factory :user do
    first_name 'John'
    last_name  'Doe'
    birthdate  { 21.years.ago }
    admin false
  end
end

When i try to run a rspec test i get following error:

NoMethodError: undefined method 'first_name' in 'user' factory!
   Method_missing at C:/jruby-9.1.17.0/lib/ruby/gems/shared/gems/factory_bot-5.0.2/lib/factory_bot/definition_proxy.rb:97
   block in (root) at <path to factory>

It seems to me the gem is correctly loaded into the project, the factoryBot code is executed. But for some reason it does not recognize the structure of the factory.

Note: - I did a bundle install/update

Prentice answered 12/3, 2019 at 10:33 Comment(4)
Try first_name { 'John' }Gullett
^^^ what Sergio said. Static attributes were removed in factory_bot 5.Stichous
@Stefan: the error message could have been better, though. It's useless as it is.Gullett
@Stefan: Yes that's the problem. Thanks! And yes the message could be better...Prentice
A
11

Like people said in the comments static attributes like first_name 'John' have been deprecated on v4 (check this guide) and then removed on v5, the alternative is to make them like dynamic attributes: first_name { 'John' }.

They even included a Rubocop to help you fix all of your factories:

rubocop \
  --require rubocop-rspec \
  --only FactoryBot/AttributeDefinedStatically \
  --auto-correct

My recommendation is to migrate slowly but surely, go from FactoryGirl to FactoryBot using a similar version, run your specs, check for all deprecation warnings, run the custom Rubocop to auto-correct your factories, then only migrate major versions after reading the changelog.

I agree the message could be a bit better, usually the main goal of deprecation is to simplify code and reduce branching logic, so once the deprecation warning was there for enough time and it is time to remove it, any detection of the old usage would be extra code that had to be removed, common result in open source projects.

Glad you found your way out.

Aubreyaubrie answered 12/3, 2019 at 12:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.