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

Inherits:
Base
  • Object
show all
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::NodePattern

#block_pattern, #send_pattern

Methods included from RSpec::Language

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

Instance Method Details

#each?(node) ⇒ Object


23
24
25
26
27
28
29
# File 'lib/rubocop/cop/rspec/iterated_expectation.rb', line 23

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

#expectation?(node) ⇒ Object


32
33
34
# File 'lib/rubocop/cop/rspec/iterated_expectation.rb', line 32

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

#on_block(node) ⇒ Object


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

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