File: iterated_expectation.rb

package info (click to toggle)
ruby-rubocop-rspec 2.16.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,892 kB
  • sloc: ruby: 22,283; makefile: 4
file content (74 lines) | stat: -rw-r--r-- 1,918 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# 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 each_numblock?(node)
        def_node_matcher :each_numblock?, <<-PATTERN
          (numblock
            (send ... :each) _ $(...)
          )
        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

        def on_numblock(node)
          each_numblock?(node) do |body|
            if single_expectation?(body, :_1) || only_expectations?(body, :_1)
              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