Sha256: 6677c05d7dbcfe1857b99c5c9145ec25c08fdbcd520af6a08fe173a60bcb1061

Contents?: true

Size: 1.51 KB

Versions: 6

Compression:

Stored size: 1.51 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module RSpec
      module FactoryBot
        # 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.
        #
        # @example
        #   # bad
        #   factory :foo, class: Foo do
        #   end
        #
        #   # good
        #   factory :foo, class: 'Foo' do
        #   end
        class FactoryClassName < Cop
          MSG = "Pass '%<class_name>s' string instead of `%<class_name>s` " \
                'constant.'
          ALLOWED_CONSTANTS = %w[Hash OpenStruct].freeze

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

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

              add_offense(cn, message: format(MSG, class_name: cn.const_name))
            end
          end

          def autocorrect(node)
            lambda do |corrector|
              corrector.replace(node.loc.expression, "'#{node.source}'")
            end
          end

          private

          def allowed?(const_name)
            ALLOWED_CONSTANTS.include?(const_name)
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rubocop-rspec-1.41.0 lib/rubocop/cop/rspec/factory_bot/factory_class_name.rb
rubocop-rspec-1.40.0 lib/rubocop/cop/rspec/factory_bot/factory_class_name.rb
rubocop-rspec-1.39.0 lib/rubocop/cop/rspec/factory_bot/factory_class_name.rb
rubocop-rspec-1.38.1 lib/rubocop/cop/rspec/factory_bot/factory_class_name.rb
rubocop-rspec-1.38.0 lib/rubocop/cop/rspec/factory_bot/factory_class_name.rb
rubocop-rspec-1.37.1 lib/rubocop/cop/rspec/factory_bot/factory_class_name.rb