Unlike many at thoughtbot, I’m actually not a fan of fakes. It’s a ton of overhead to mock the API, and it’s too easy to get something wrong and discover it on Staging/Production. If the service is one that can be reset between test runs (e.g. You’re scraping Google/Twitter/whatever, or it’s something like S3), I prefer to use VCR. There’s a couple of caveats to doing this effectively.
- Set your cassettes to expire after a few days. I usually do 3. You want to hit the actual API at a reasonable frequency.
- Add your cassettes to .gitignore. They exist only to make your tests run faster. You should be able to delete the entire directory and have your specs pass.
- If integration with the service requires an API key, consider wrapping specs that hit the API in
if ENV['FOO_API_KEY'].present?. If too many keys are required to run the test suite, it can be frustrating for new developers rolling onto the project.
- The only things that should require VCR are the unit tests for the class that interacts directly with that API, and integration tests. Make sure you use a stub instead of the class that hits the service in unit tests for collaborating objects.
Always keep in mind that you’re attempting to test your real integration with the API. Do not think of VCR as a mocking service, and don’t try and use it as a replacement for Web Mocks. If you only use it as a helper to make your tests run faster and/or avoid hitting API limits, it can work beautifully.
For cases where you cannot reasonably reset or setup test data for an API, then it’s definitely worthwhile to look at setting up a fake or just using WebMock. In this case, however, I’d look to see if CASHNet has a sandbox mode of some kind you can use in tests.