When coding sometimes it’s difficult to think through edge cases of what will
happen when. Instead of thinking too hard about it let RSpec do the heavy
lifting for you! Pretend you have the following Fetcher
class responsible for
performing http requests and retrying when the host sever has problems:
|
Right away we can see that the fetch
method is doing the heavy lifting in this
class. Just looking at it causes my head to start spinning. Versus trying to
run this code in your head to reason if the code is working correctly let’s test
it instead!
|
The meat and potatoes of the test here is making sure that sleep
is called for
each retry. On lines 23 – 25 we can see that if the response always comes back
as a 503
then we expect sleep to be called with 2
, 4
, and 8
. The
ordered
part of RSpec mocks preserves the order. Another great use of
orderd
is on lines 31 – 33. Here we only want it to fail twice then succeed
on the third attempt. One thing I learned was this only works with expect
.
The following code will not work.
|
In this case, allow
overrides previous mock setups. When this code is run
the response
will always return 200. If you want to check this out for
youself I threw it up on github.