class RuboCop::Cop::RSpec::ReturnFromStub
allow(Foo).to receive(:bar) { bar.baz }
# also good as the returned value is dynamic
expect(Foo).to receive(:bar).and_return(“baz”)
allow(Foo).to receive(:bar).and_return(“baz”)
# good
expect(Foo).to receive(:bar) { “baz” }
allow(Foo).to receive(:bar) { “baz” }
# bad
@example ‘EnforcedStyle: and_return`
allow(Foo).to receive(:bar).and_return(bar.baz)
# also good as the returned value is dynamic
expect(Foo).to receive(:bar) { “baz” }
allow(Foo).to receive(:bar) { “baz” }
# good
expect(Foo).to receive(:bar).and_return(“baz”)
allow(Foo).to receive(:bar).and_return(“baz”)
# bad
@example `EnforcedStyle: block`
This cop can be configured using the `EnforcedStyle` option
are the result would be different
where the returned value is constant. Ignores dynamic returned values
Enforces either `and_return` or block-style return in the cases
Checks for consistent style of stub’s return setting.
def autocorrect(node)
def autocorrect(node) if style == :block AndReturnCallCorrector.new(node) else BlockBodyCorrector.new(node) end end
def check_and_return_call(node)
def check_and_return_call(node) and_return_value(node) do |and_return, args| unless dynamic?(args) add_offense( and_return, location: :selector, message: MSG_BLOCK ) end end end
def check_block_body(block)
def check_block_body(block) body = block.body unless dynamic?(body) # rubocop:disable Style/GuardClause add_offense( block, location: :begin, message: MSG_AND_RETURN ) end end
def dynamic?(node)
def dynamic?(node) node && !node.recursive_literal_or_const? end
def on_block(node)
def on_block(node) return unless contains_stub?(node) return unless style == :and_return check_block_body(node) end
def on_send(node)
def on_send(node) return unless contains_stub?(node) return unless style == :block check_and_return_call(node) end