Over the past couple of weeks, I’ve been trying to wrap my head around writing good test coverage for my Adapter class that communicates with an external web service.
Yesterday afternoon I was able to get my tests to pass, but to be honest, I don’t understand why they’re green, and am of a mind that I’m either receiving false positives, or testing something I shouldn’t (i.e Faraday’s/WebMock’s behavior instead of my Adapter class’ behavior). I ended up going with WebMock instead of the VCR gem, as I was spending (IMO) too much time attempting to implement a dependency and not enough focus on actually understanding and solving the challenge of adding coverage to my Adapter.
Here is my partially finished Adapter tests:
And my RSpec output:
Looks like I need to remove the blocks from my last two specs so they can turn yellow (Pending) instead of green (Passing).
At first I was surprised that my specs passed, but upon further search realized that
to_return may be a method from WebMock and not Rspec. Rspec does have an
and_return method, although I haven’t had success so far in using it. I prefer using blocks anyhow.
Here’s a link to the entire page from the above image snippet, in case you’d like to further look at this.
Resources I’ve Learned From
There is good news! I have found many a resource on the VCR gem, RSpec, and related Web Service testing.
I’ll list what I’ve been reading with the hopes that they provide you insight as well:
- Tests and Mocks in Rspec
- A Pattern for Stubbing Out APIs With Rspec
- Stubbing External Service Calls with RSpec
- Testing Faraday with VCR and MiniTest in a Rails App
- Testing Third Party HTTP APIs – Richard Livsey and Bartosz Blimke
- Testing Remote Services with WebMock and VCR
- Testing Rails JSON APIs with RSpec
- How to Stub External Services in Tests by: Harlow Ward via thoughtbot
- Testing an external API using RSpec’s request specs
- Rails Acceptance Tests – stubbing out external service calls
And last but not least, here’s my latest AirPair video with Adam that I received today. It covers him instructing me about testing out my Adapter class. I’ve only been able to review a little under half of it so far, but I can already tell that I’ll have more insight from the experts to share about coverage for web services in a future post.