Note this article was published first on the asquera blog, see the post there.
Writing web services or applications that consume APIs is a common part of web development. Be it either a web service that is developed internally or by using an existing API from a 3rd party.
When writing tests against an external API one can face a number of issues
- tests fail due to connectivity issues
- service has a limited hit rate and responds with errors after a while
- service does not exist yet or is incomplete
- authentication is not possible or access is restricted
- no development / staging server available
- communication with the API leads to high payload or has slow response times
- interacting with the API directly might lead to side effects in the service
To avoid these issues we want our tests to not hit any 3rd party API while still respecting the API functions available to us. Furthermore our test suite needs to pass in a repeatable manner, fast and without any side effects.
When we develop against an external API a common way to communicate with it is by using a dedicated library from either a 3rd party or by writing one ourselves. Typically there is already a ruby library available to us if the development is for a known platform such as twitter. But even when it's for an internal API it makes sense to group the functionality into a single library to provide reusability or to offer others a convenient way to interact with our API.
There are a couple of solutions available that differ depending on the context and the requirements of the API.