rubocop-factory_bot icon indicating copy to clipboard operation
rubocop-factory_bot copied to clipboard

FactoryBot/FactoryAssociationWithStrategy false positive with keyword argument

Open jcoyne opened this issue 2 years ago • 5 comments

spec/factories/holdings.rb:7:14: C: FactoryBot/FactoryAssociationWithStrategy: Use an implicit, explicit or inline definition instead of hard coding a strategy for setting association within factory.
      item { build(:item, :available, location:) }
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I don't think there is another way to write this given that location references another transient:

FactoryBot.define do
  factory :holding do
    transient do
      location factory: :gre_stacks
      item { build(:item, :available, location:) }
    end
    
    ...

jcoyne avatar Sep 18 '23 20:09 jcoyne

How does this work? Is it really transient? https://github.com/thoughtbot/factory_bot/blob/main/GETTING_STARTED.md#with-associations

You could still refer to ‘location’ if you used ‘association’ instead of ‘build’, right?

With this in mind, can this be written as:

FactoryBot.define do
  factory :holding do
    location factory: :gre_stacks
    item { association(:item, :available, location:) }
  end

?

pirj avatar Sep 18 '23 20:09 pirj

@pirj item is not really a property of holding, it's a transient that is later used by initialize_with, so I don't think association will work.

jcoyne avatar Sep 18 '23 21:09 jcoyne

I see. Thanks for reporting. Might be a duplicate of https://github.com/rubocop/rubocop-factory_bot/issues/61, but not necessarily.

pirj avatar Sep 18 '23 22:09 pirj

This cop needs to be fixed not to bark inside transient blocks

Abdullah-l avatar Aug 10 '24 17:08 Abdullah-l

A PR is welcome, @Abdullah-l

pirj avatar Aug 10 '24 17:08 pirj