class RuboCop::Cop::RSpec::ReturnFromStub
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`
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` (default)
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 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.loc.selector, message: MSG_BLOCK) do |corr| AndReturnCallCorrector.new(and_return).call(corr) end end end end
def check_block_body(block)
def check_block_body(block) body = block.body return if dynamic?(body) add_offense(block.loc.begin, message: MSG_AND_RETURN) do |corrector| BlockBodyCorrector.new(block).call(corrector) end end
def dynamic?(node)
def dynamic?(node) node && !node.recursive_literal_or_const? end
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler return unless style == :and_return return unless stub_with_block?(node) check_block_body(node) end
def on_send(node)
def on_send(node) return unless style == :block return unless contains_stub?(node) check_and_return_call(node) end