Class: RuboCop::Cop::Momocop::FactoryBotInlineAssociation

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
Momocop::Helpers::FactoryBotHelper
Defined in:
lib/rubocop/cop/momocop/factory_bot_inline_association.rb

Overview

Enforces inline association definitions in FactoryBot factories.

Examples:

# bad
factory :blog_post do
  association(:user, factory: :foo)
  association(:admin, factory: [:foo, :trait])
end

# good
factory :blog_post do
  user { association :foo }
  admin { association :foo, :trait }
end

Constant Summary collapse

MSG =
'Use inline association definition instead of separate `association` method call.'
RESTRICT_ON_SEND =
%i[association].freeze

Constants included from Momocop::Helpers::FactoryBotHelper

Momocop::Helpers::FactoryBotHelper::RUBOCOP_HELPER_METHODS

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rubocop/cop/momocop/factory_bot_inline_association.rb', line 32

def on_send(node)
  return unless inside_factory_bot_define?(node)
  return unless inside_factory_bot_factory?(node)

  add_offense(node.loc.selector, message: MSG) do |corrector|
    association_name = node.arguments.first.value
    options = node.arguments.at(1)

    convert_options(options) in {
      factory_option:, rest_options:
    }
    factory = factory_option || ":#{association_name}"
    replacement =
      if rest_options.empty?
        "#{association_name} { association #{factory} }"
      else
        rest_options_source = rest_options.map(&:source).join(', ')
        "#{association_name} { association #{factory}, #{rest_options_source} }"
      end
    corrector.replace(node, replacement)
  end
end