Class: RuboCop::Cop::FactoryBot::FactoryAssociationWithStrategy

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/factory_bot/factory_association_with_strategy.rb

Overview

Use definition in factory association instead of hard coding a strategy.

Examples:

# bad - only works for one strategy
factory :foo do
  profile { create(:profile) }
end

# good - implicit
factory :foo do
  profile
end

# good - explicit
factory :foo do
  association :profile
end

# good - inline
factory :foo do
  profile { association :profile }
end

Constant Summary collapse

MSG =
'Use an implicit, explicit or inline definition instead of ' \
'hard coding a strategy for setting association within factory.'
HARDCODED =
Set.new(%i[create build build_stubbed]).freeze

Instance Method Summary collapse

Instance Method Details

#factory_declaration(node) ⇒ Object



36
37
38
39
40
# File 'lib/rubocop/cop/factory_bot/factory_association_with_strategy.rb', line 36

def_node_matcher :factory_declaration, <<~PATTERN
  (block (send nil? {:factory :trait} ...)
    ...
  )
PATTERN

#factory_strategy_association(node) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/rubocop/cop/factory_bot/factory_association_with_strategy.rb', line 43

def_node_matcher :factory_strategy_association, <<~PATTERN
  (block
    (send nil? _association_name)
    (args)
    < $(send nil? HARDCODED ...) ... >
  )
PATTERN

#on_block(node) ⇒ Object

rubocop:disable InternalAffairs/NumblockHandler



51
52
53
54
55
56
57
58
59
# File 'lib/rubocop/cop/factory_bot/factory_association_with_strategy.rb', line 51

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  factory_declaration(node) do
    node.each_node do |statement|
      factory_strategy_association(statement) do |hardcoded_association|
        add_offense(hardcoded_association)
      end
    end
  end
end