#RSpec / How to write specs to test a service that makes calls to an external API?
Not solved Solved
about 2 months ago

I wrote a service that makes calls to an external API. This service is in app/services/...

Here are all my questions : - Should I write "Feature" specs, or "Request" specs? (or something else?) - How can I simulate the JSON sent by the external API? - What are the best practices in this situation? Any piece of advices?

Fyi, my service is POOR. Just a Ruby class with only one instance method at the moment (and several private methods).

Thank in advance for your help.


about 2 months ago

Hi db, We usually use VCR (https://relishapp.com/vcr/vcr/v/1-7-0/docs/getting-started) in those instances, which helps us speed up the test suits. Basically, assuming your app will do multiple API calls in different places, it would take too long to actually perform these calls. Rather than calling, then, we use VCR, which performs the calls once, saves them, and then imitates the responses every time your tests run. One thing to watch our for then, since you're no longer really issuing the calls, is that your VCR cassettes might become outdates (the external API changes, and hence the real response changes). What that means is that, then, it'll become your responsibility to ensure over time that your VCRs are up to date with the external API. This is quite well documented, and comes in form of a re-recording functionality. You could also just manually delete these VCRs from your system, which would always trigger a new recording. So much for setup. As far as the specs themselves go, we usually assert the HTTP status of the response (201, 404, etc.) to see whether or not the call succeeded or failed, and then, if necessary, you could even test certain aspects of the response you got (e.g. format of the JSON and if it includes what you need).

I hope this helps a bit and hit me up if you have more questions. Certainly no pro in this, but this is the little experience I got :)

Submit your answer