Sha256: fec43b798c2bfe958f56e31ce9eac09408f4cdebaf2880a00b5b3973e48f4471

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
      # Check that `all` matcher is used instead of iterating over an array.
      #
      # @example
      #   # bad
      #   it 'validates users' do
      #     [user1, user2, user3].each { |user| expect(user).to be_valid }
      #   end
      #
      #   # good
      #   it 'validates users' do
      #     expect([user1, user2, user3]).to all(be_valid)
      #   end
      class IteratedExpectation < Base
        MSG = 'Prefer using the `all` matcher instead ' \
                  'of iterating over an array.'

        def_node_matcher :each?, <<-PATTERN
          (block
            (send ... :each)
            (args (arg $_))
            $(...)
          )
        PATTERN

        def_node_matcher :expectation?, <<-PATTERN
          (send (send nil? :expect (lvar %)) :to ...)
        PATTERN

        def on_block(node)
          each?(node) do |arg, body|
            if single_expectation?(body, arg) || only_expectations?(body, arg)
              add_offense(node.send_node)
            end
          end
        end

        private

        def single_expectation?(body, arg)
          expectation?(body, arg)
        end

        def only_expectations?(body, arg)
          body.each_child_node.all? { |child| expectation?(child, arg) }
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
rubocop-rspec-2.0.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-2.0.0.pre lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.44.1 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.44.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.43.2 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.43.1 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.43.0 lib/rubocop/cop/rspec/iterated_expectation.rb