class RuboCop::Cop::RSpec::ReturnFromStub
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
@example `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)
@example `EnforcedStyle: and_return`
# 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 }
Constants
- MSG_AND_RETURN
- MSG_BLOCK
Public Instance Methods
autocorrect(node)
click to toggle source
# File lib/rubocop/cop/rspec/return_from_stub.rb, line 61 def autocorrect(node) if style == :block AndReturnCallCorrector.new(node) else BlockBodyCorrector.new(node) end end
on_block(node)
click to toggle source
# File lib/rubocop/cop/rspec/return_from_stub.rb, line 54 def on_block(node) return unless contains_stub?(node) return unless style == :and_return check_block_body(node) end
on_send(node)
click to toggle source
# File lib/rubocop/cop/rspec/return_from_stub.rb, line 47 def on_send(node) return unless contains_stub?(node) return unless style == :block check_and_return_call(node) end
Private Instance Methods
check_and_return_call(node)
click to toggle source
# File lib/rubocop/cop/rspec/return_from_stub.rb, line 71 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
check_block_body(block)
click to toggle source
# File lib/rubocop/cop/rspec/return_from_stub.rb, line 83 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
dynamic?(node)
click to toggle source
# File lib/rubocop/cop/rspec/return_from_stub.rb, line 94 def dynamic?(node) node && !node.recursive_literal_or_const? end