Class: RuboCop::Cop::RSpec::Yield

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

Overview

Checks for calling a block within a stub.

Examples:

# bad
allow(foo).to receive(:bar) { |&block| block.call(1) }

# good
expect(foo).to receive(:bar).and_yield(1)

Constant Summary collapse

MSG =
'Use `.and_yield`.'

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

#block_arg(node) ⇒ Object


24
# File 'lib/rubocop/cop/rspec/yield.rb', line 24

def_node_matcher :block_arg, '(args (blockarg $_))'

#block_call?(node) ⇒ Object


27
# File 'lib/rubocop/cop/rspec/yield.rb', line 27

def_node_matcher :block_call?, '(send (lvar %) :call ...)'

#method_on_stub?(node) ⇒ Object


21
# File 'lib/rubocop/cop/rspec/yield.rb', line 21

def_node_search :method_on_stub?, '(send nil? :receive ...)'

#on_block(node) ⇒ Object


29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rubocop/cop/rspec/yield.rb', line 29

def on_block(node)
  return unless method_on_stub?(node.send_node)

  block_arg(node.arguments) do |block|
    if calling_block?(node.body, block)
      range = block_range(node)

      add_offense(range) do |corrector|
        autocorrect(corrector, node, range)
      end
    end
  end
end