Skip to content

Instantly share code, notes, and snippets.

@mchung
Last active January 4, 2017 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mchung/4c8566e0a29f6778103be764ffa1ab34 to your computer and use it in GitHub Desktop.
Save mchung/4c8566e0a29f6778103be764ffa1ab34 to your computer and use it in GitHub Desktop.
TIL difference between RSpec's syntaxes for returning a mocked value.
(byebug) hello = instance_double("Planet")
#<InstanceDouble(Planet) (anonymous)>
# Using RSpec block syntax to specific a return value.
(byebug) allow(hello).to receive(:world) { "hello, world" }
#<RSpec::Mocks::VerifyingMessageExpectation #<InstanceDouble(Planet) (anonymous)>.world(any arguments)>
# We get the value we intended
(byebug) hello.world
"hello, world"
# Notice that it's a different string instance each invocation
(byebug) hello.world.object_id
70139543692820
(byebug) hello.world.object_id
70139543680920
# Now, using and_return to specify a return value.
(byebug) allow(hello).to receive(:world).and_return("hello, world") # AND_RETURN
#<RSpec::Mocks::VerifyingMessageExpectation #<InstanceDouble(Planet) (anonymous)>.world(any arguments)>
(byebug) hello.world
"hello, world"
# Notice here and_return returns the same string object.
(byebug) hello.world.object_id
70139543677620
(byebug) hello.world.object_id
70139543677620
# Blocks are re-evaluated each time. Obvious in hindsight, though not at first.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment