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

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

Instance Method Details

#block_arg(node) ⇒ Object



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

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

#block_call?(node) ⇒ Object



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

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

#method_on_stub?(node) ⇒ Object



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

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

#on_block(node) ⇒ Object

rubocop:disable InternalAffairs/NumblockHandler



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

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  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