Class: RuboCop::Cop::FactoryBot::NoAssociationsInFactory

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

Overview

Forbids declaring associations inside a ‘factory`/`trait` block. An association is a bare attribute call with no value (e.g. `customer`), which triggers cascading object creation and callbacks. Set the association manually in the spec instead.

Examples:

# bad
factory :payment do
  amount { 100.0 }
  customer
end

# good
factory :payment do
  amount { 100.0 }
end

Constant Summary collapse

MSG =
'Do not declare associations in factories — set them manually in the spec.'
CONTAINER_METHODS =
%i[factory trait].freeze
DSL_KEYWORDS =

FactoryBot DSL methods that are bare calls but are NOT associations.

%i[skip_create initialize_with].freeze

Instance Method Summary collapse

Instance Method Details

#on_block(node) ⇒ Object Also known as: on_numblock, on_itblock



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rubocop/cop/factory_bot/no_associations_in_factory.rb', line 32

def on_block(node)
  return unless container_block?(node)

  body = node.body
  return unless body

  statements = body.begin_type? ? body.children : [body]

  statements.each do |statement|
    add_offense(statement.loc.selector) if association_call?(statement)
  end
end