Class: RuboCop::Cop::FactoryBot::FactoryClassName

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/factory_bot/factory_class_name.rb

Overview

Use string value when setting the class attribute explicitly.

This cop would promote faster tests by lazy-loading of application files. Also, this could help you suppress potential bugs in combination with external libraries by avoiding a preload of application files from the factory files.

Examples:

# bad
factory :foo, class: Foo do
end

# good
factory :foo, class: 'Foo' do
end

Constant Summary collapse

MSG =
"Pass '%<class_name>s' string instead of `%<class_name>s` " \
'constant.'
ALLOWED_CONSTANTS =
%w[Hash OpenStruct].freeze
RESTRICT_ON_SEND =
%i[factory].freeze

Instance Method Summary collapse

Instance Method Details

#class_name(node) ⇒ Object



31
32
33
# File 'lib/rubocop/cop/factory_bot/factory_class_name.rb', line 31

def_node_matcher :class_name, <<~PATTERN
  (send _ :factory _ (hash <(pair (sym :class) $(const ...)) ...>))
PATTERN

#on_send(node) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/rubocop/cop/factory_bot/factory_class_name.rb', line 35

def on_send(node)
  class_name(node) do |cn|
    next if allowed?(cn.const_name)

    msg = format(MSG, class_name: cn.const_name)
    add_offense(cn, message: msg) do |corrector|
      corrector.replace(cn, "'#{cn.source}'")
    end
  end
end