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: 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 }
@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)
Constants
- MSG_AND_RETURN
- MSG_BLOCK
- RESTRICT_ON_SEND
Public Instance Methods
Source
# 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
Source
# 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
Private Instance Methods
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.loc.selector, message: MSG_BLOCK) do |corr| AndReturnCallCorrector.new(and_return).call(corr) end end end end
Source
# File lib/rubocop/cop/rspec/return_from_stub.rb, line 81 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
Source
# File lib/rubocop/cop/rspec/return_from_stub.rb, line 90 def dynamic?(node) node && !node.recursive_literal_or_const? end