Skip to content

FactoryBot/FactoryAssociationWithStrategy cop error when something is defined in a transient #61

@schinery

Description

@schinery

Not sure if this is related to #54 but the issue I am having is that when something has been defined in a transient block that is using build or create, then rubocop throws a FactoryBot/FactoryAssociationWithStrategy error thinking it is an association.

For example this:

# frozen_string_literal: true

FactoryBot.define do
  factory :visit, class: "Visit" do
    transient do
      address { build(:address) }
    end

    visitable factory: %i[job]

    before(:create) do |visit, evaluator|
      visit.visitable.address = evaluator.address 
    end
  end
end

Leads to this:

spec/factories/visits.rb:6:17: C: FactoryBot/FactoryAssociationWithStrategy: Use an implicit, explicit or inline definition instead of hard coding a strategy for setting association within factory.
      address { build(:address) }

I know in this example I could get around this by changing the above code to address { nil } and evaluator.address || build(:address) but I have some other factories doing the same that aren't so straightforward to amend.

Rubocop Gems:

 bundle exec gem list rubocop

*** LOCAL GEMS ***

rubocop (1.54.2)
rubocop-ast (1.29.0)
rubocop-capybara (2.18.0)
rubocop-factory_bot (2.23.1)
rubocop-faker (1.1.0)
rubocop-rails (2.20.2)
rubocop-rake (0.6.0)
rubocop-rspec (2.22.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