Sha256: 330e9fdf60cea090100afc2b9b31ad2ed2b6c56ec040ab46e036197421dd82e4

Contents?: true

Size: 1.34 KB

Versions: 13

Compression:

Stored size: 1.34 KB

Contents

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 < Cop
        MSG = 'Prefer using the `all` matcher instead ' \
                  'of iterating over an array.'.freeze

        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.children.first, location: :expression)
            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

13 entries across 13 versions & 1 rubygems

Version Path
rubocop-rspec-1.27.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.26.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.25.1 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.25.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.24.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.23.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.22.2 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.22.1 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.22.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.21.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.20.1 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.20.0 lib/rubocop/cop/rspec/iterated_expectation.rb
rubocop-rspec-1.19.0 lib/rubocop/cop/rspec/iterated_expectation.rb