Sha256: 701fcad07d13a298c6e2fe7aa9838c3803f3449e99d1c6d5421b4765c04b2fc7

Contents?: true

Size: 1.46 KB

Versions: 14

Compression:

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

        # @!method each?(node)
        def_node_matcher :each?, <<-PATTERN
          (block
            (send ... :each)
            (args (arg $_))
            $(...)
          )
        PATTERN

        # @!method expectation?(node)
        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)
          return false unless body.each_child_node.any?

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

Version data entries

14 entries across 12 versions & 2 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-rspec-2.12.1/lib/rubocop/cop/rspec/iterated_expectation.rb
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-rspec-2.9.0/lib/rubocop/cop/rspec/iterated_expectation.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-rspec-2.12.1/lib/rubocop/cop/rspec/iterated_expectation.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-rspec-2.9.0/lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-2.12.1 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-2.12.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-2.11.1 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-2.11.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-2.10.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-2.9.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-2.8.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-2.7.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-2.6.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-2.5.0 lib/rubocop/cop/rspec/iterated_expectation.rb