Skip to content

FactoryBot/AssociationStyle autocorrects to incorrect code #82

@a-lavis

Description

@a-lavis

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions