Method: RSpec::Mocks::MessageExpectation#and_return

Defined in:
lib/rspec/mocks/message_expectation.rb

#and_return(value) ⇒ nil #and_return(first_value, second_value) ⇒ nil

Tells the object to return a value when it receives the message. Given more than one value, the first value is returned the first time the message is received, the second value is returned the next time, etc, etc.

If the message is received more times than there are values, the last value is returned for every subsequent call.

Examples:

allow(counter).to receive(:count).and_return(1)
counter.count # => 1
counter.count # => 1

allow(counter).to receive(:count).and_return(1,2,3)
counter.count # => 1
counter.count # => 2
counter.count # => 3
counter.count # => 3
counter.count # => 3
# etc

Returns:

  • (nil)

    No further chaining is supported after this.



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/rspec/mocks/message_expectation.rb', line 71

def and_return(first_value, *values)
  raise_already_invoked_error_if_necessary(__method__)
  if negative?
    raise "`and_return` is not supported with negative message expectations"
  end

  if block_given?
    raise ArgumentError, "Implementation blocks aren't supported with `and_return`"
  end

  values.unshift(first_value)
  @expected_received_count = [@expected_received_count, values.size].max unless ignoring_args? || (@expected_received_count == 0 && @at_least)
  self.terminal_implementation_action = AndReturnImplementation.new(values)

  nil
end