Sha256: 578afad12ae94ac5da15a08afc7727f5f454c000d9528eaec284119b31ea9b87

Contents?: true

Size: 1.77 KB

Versions: 12

Compression:

Stored size: 1.77 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module RSpec
      # Checks if there is a let/subject that overwrites an existing one.
      #
      # @example
      #   # bad
      #   let(:foo) { bar }
      #   let(:foo) { baz }
      #
      #   subject(:foo) { bar }
      #   let(:foo) { baz }
      #
      #   let(:foo) { bar }
      #   let!(:foo) { baz }
      #
      #   # good
      #   subject(:test) { something }
      #   let(:foo) { bar }
      #   let(:baz) { baz }
      #   let!(:other) { other }
      class OverwritingSetup < Cop
        MSG = '`%<name>s` is already defined.'

        def_node_matcher :setup?, (Helpers::ALL + Subject::ALL).block_pattern
        def_node_matcher :first_argument_name, '(send _ _ ({str sym} $_))'

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

          find_duplicates(node.body) do |duplicate, name|
            add_offense(
              duplicate,
              message: format(MSG, name: name)
            )
          end
        end

        private

        def find_duplicates(node)
          setup_expressions = Set.new
          node.each_child_node(:block) do |child|
            next unless common_setup?(child)

            name = if child.send_node.arguments?
                     first_argument_name(child.send_node).to_sym
                   else
                     :subject
                   end

            yield child, name unless setup_expressions.add?(name)
          end
        end

        def common_setup?(node)
          return false unless setup?(node)

          # Search only for setup with basic_literal arguments (e.g. :sym, :str)
          # or no arguments at all.
          node.send_node.arguments.all?(&:basic_literal?)
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
rubocop-rspec-1.42.0 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.41.0 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.40.0 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.39.0 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.38.1 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.38.0 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.37.1 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.37.0 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.36.0 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.35.0 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.34.1 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.34.0 lib/rubocop/cop/rspec/overwriting_setup.rb