Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating from FactoryGirl to factoryBot results in NoMethodError

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

like image 899
denBelg Avatar asked Dec 24 '22 00:12

denBelg


1 Answers

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.

like image 51
Danilo Cabello Avatar answered Dec 30 '22 08:12

Danilo Cabello