rubocop / rubocop-factory_bot

Code style checking for factory_bot files.
https://docs.rubocop.org/rubocop-factory_bot
MIT License
47 stars 13 forks source link

`FactoryBot/AssociationStyle` autocorrects to incorrect code #82

Open a-lavis opened 1 year ago

a-lavis commented 1 year ago

Consider the following file:

# frozen_string_literal: true

FactoryBot.define do
  factory :post do
    association :user, strategy: :create
  end
end

This triggers a FactoryBot/AssociationStyle offense. When I run rubocop -A on the file, I see:

Inspecting 1 file
C

Offenses:

test/factories/posts.rb:5:5: C: [Corrected] FactoryBot/AssociationStyle: Use implicit style to define associations.
    association :user, strategy: :create
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
test/factories/posts.rb:5:5: C: [Corrected] FactoryBot/AttributeDefinedStatically: Use a block to declare attribute values.
    user strategy: :create
    ^^^^^^^^^^^^^^^^^^^^^^

1 file inspected, 2 offenses detected, 2 offenses corrected

The resulting file is:

# frozen_string_literal: true

FactoryBot.define do
  factory :post do
    user { { strategy: :create } }
  end
end

This defines user to be a hash with the key :strategy and the value :create, instead of an association to a User model that is created. This is not equivalent to association :user, strategy: :create.

Instead, should we be autocorrecting this code to the following?

# frozen_string_literal: true

FactoryBot.define do
  factory :post do
    user { association :user, strategy: :create }
  end
end

Or should we not trigger an offense at all?


Here is my .rubocop.yml:

require:
  - rubocop-factory_bot

AllCops:
  NewCops: enable
  TargetRubyVersion: 3.2

I am using rubocop 1.57.1 and rubocop-factory_bot 2.24.0.

ydakuka commented 1 year ago

duplicate https://github.com/rubocop/rubocop-factory_bot/issues/79