High-Fidelity Fakes

When you work with rspec-mocks, you’re using fake behavior supplied by RSpec. There are other kinds of test doubles, though. You can use an alternative implementation designed to drop into your tests in place of the real thing. Because these mimic the original library’s interface and behavior closely, we call them high-fidelity fakes.

For instance, the FakeFS gem makes it easy to test code that interacts with the filesystem.[109] FakeRedis acts just like the Redis data store but doesn’t require a network connection or a running server.[110] If you use Braintree for credit-card processing, Fake Braintree can stand in during testing.[111]

Sometimes, a library ships with its own high-fidelity fake. The Fog gem, which wraps cloud services like Amazon’s, comes with a mocks mode built in.[112] If you’re developing a library that calls external services, your users will be grateful if you provide a high-fi fake. You can write one set of specs to check both the real and fake implementations using RSpec’s shared examples. We discussed these in Sharing Examples.

Fakes are particularly useful for HTTP APIs. Alas, most API clients don’t include a high-fi fake. Fortunately, you can put one together fairly quickly using the VCR gem (written by Myron, one of the co-authors of this book).[113] When you first use VCR from your tests, it will record network requests to the real API together with their responses. Later test runs will use the recorded data instead of making real API calls.

In the next section, we’d like to show you what it’s like to test with a high-fidelity fake—specifically, the StringIO class that ships with Ruby. With it, you can simulate I/O to the console, a disk file, the network, pipes, and more.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset