Class: RuboCop::Cop::RSpec::ReturnFromStub

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

Overview

Checks for consistent style of stub’s return setting.

Enforces either ‘and_return` or block-style return in the cases where the returned value is constant. Ignores dynamic returned values are the result would be different

This cop can be configured using the ‘EnforcedStyle` option

Examples:

‘EnforcedStyle: and_return` (default)

# bad
allow(Foo).to receive(:bar) { "baz" }
expect(Foo).to receive(:bar) { "baz" }

# good
allow(Foo).to receive(:bar).and_return("baz")
expect(Foo).to receive(:bar).and_return("baz")
# also good as the returned value is dynamic
allow(Foo).to receive(:bar) { bar.baz }

‘EnforcedStyle: block`

# bad
allow(Foo).to receive(:bar).and_return("baz")
expect(Foo).to receive(:bar).and_return("baz")

# good
allow(Foo).to receive(:bar) { "baz" }
expect(Foo).to receive(:bar) { "baz" }
# also good as the returned value is dynamic
allow(Foo).to receive(:bar).and_return(bar.baz)

Defined Under Namespace

Classes: AndReturnCallCorrector, BlockBodyCorrector

Constant Summary collapse

MSG_AND_RETURN =
'Use `and_return` for static values.'
MSG_BLOCK =
'Use block for static values.'
RESTRICT_ON_SEND =
%i[and_return].freeze

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

#and_return_value(node) ⇒ Object



51
52
53
# File 'lib/rubocop/cop/rspec/return_from_stub.rb', line 51

def_node_search :and_return_value, <<~PATTERN
  $(send _ :and_return $(...))
PATTERN

#contains_stub?(node) ⇒ Object



45
# File 'lib/rubocop/cop/rspec/return_from_stub.rb', line 45

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

#on_block(node) ⇒ Object

rubocop:disable InternalAffairs/NumblockHandler



62
63
64
65
66
67
# File 'lib/rubocop/cop/rspec/return_from_stub.rb', line 62

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  return unless style == :and_return
  return unless stub_with_block?(node)

  check_block_body(node)
end

#on_send(node) ⇒ Object



55
56
57
58
59
60
# File 'lib/rubocop/cop/rspec/return_from_stub.rb', line 55

def on_send(node)
  return unless style == :block
  return unless contains_stub?(node)

  check_and_return_call(node)
end

#stub_with_block?(node) ⇒ Object



48
# File 'lib/rubocop/cop/rspec/return_from_stub.rb', line 48

def_node_matcher :stub_with_block?, '(block #contains_stub? ...)'