Last active
January 4, 2017 06:32
-
-
Save mchung/4c8566e0a29f6778103be764ffa1ab34 to your computer and use it in GitHub Desktop.
TIL difference between RSpec's syntaxes for returning a mocked value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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