Sha256: 1b222e173e0f556b56ddca7207c35bf5c95a29d00e5d351092a66c21bd6fd8cb

Contents?: true

Size: 1.34 KB

Versions: 7

Compression:

Stored size: 1.34 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.'.freeze

        def_node_matcher :setup?, <<-PATTERN
          (block (send nil? {:let :let! :subject} (sym $_)) ...)
        PATTERN

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

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

        private

        def find_duplicates(node)
          setup_expressions = Set.new
          node.each_child_node do |child|
            setup?(child) do |name|
              yield child, name unless setup_expressions.add?(name)
            end
          end
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
rubocop-rspec-1.25.1 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.25.0 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.24.0 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.23.0 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.22.2 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.22.1 lib/rubocop/cop/rspec/overwriting_setup.rb
rubocop-rspec-1.22.0 lib/rubocop/cop/rspec/overwriting_setup.rb