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

Inherits:
Cop
  • Object
show all
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/rspec/yield.rb

Overview

This cop checks for calling a block within a stub.

Examples:

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

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

Constant Summary collapse

MSG =
'Use `.and_yield`.'

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Constants included from RSpec::Language

RSpec::Language::ALL, RSpec::Language::RSPEC

Instance Method Summary collapse

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#autocorrect(node) ⇒ Object



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

def autocorrect(node)
  lambda do |corrector|
    node_range = range_with_surrounding_space(
      range: block_range(node), side: :left
    )
    corrector.replace(node_range, generate_replacement(node.body))
  end
end

#on_block(node) ⇒ Object



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

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

  block_arg(node.arguments) do |block|
    if calling_block?(node.body, block)
      add_offense(node, location: block_range(node))
    end
  end
end