Class: RuboCop::Cop::RSpec::IteratedExpectation

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rspec/iterated_expectation.rb

Overview

Check that ‘all` matcher is used instead of iterating over an array.

Examples:

# 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

Constant Summary collapse

MSG =
'Prefer using the `all` matcher instead ' \
'of iterating over an array.'

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #explicit_rspec?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#each?(node) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/rubocop/cop/rspec/iterated_expectation.rb', line 26

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

#each_numblock?(node) ⇒ Object



35
36
37
38
39
# File 'lib/rubocop/cop/rspec/iterated_expectation.rb', line 35

def_node_matcher :each_numblock?, <<~PATTERN
  (numblock
    (send ... :each) _ (...)
  )
PATTERN

#expectation?(node) ⇒ Object



42
43
44
# File 'lib/rubocop/cop/rspec/iterated_expectation.rb', line 42

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

#on_block(node) ⇒ Object



46
47
48
49
50
# File 'lib/rubocop/cop/rspec/iterated_expectation.rb', line 46

def on_block(node)
  each?(node) do |arg|
    check_offense(node, arg)
  end
end

#on_numblock(node) ⇒ Object



52
53
54
55
56
# File 'lib/rubocop/cop/rspec/iterated_expectation.rb', line 52

def on_numblock(node)
  each_numblock?(node) do
    check_offense(node, :_1)
  end
end