I was happily prototyping a series of API endpoints in PHP when I realized that unit testing couldn’t give me a realistic measure of quality assurance. Historically, I’ve found unit tests great for covering specific algorithms and routines, but poor at simulating real client experiences over the web. The best way to assess an API is through the eyes of a client that’s architecturally decoupled from the API codebase. Simulate an HTTP request is not the same as actually making said request. Test-savvy engineers will recognize this as integration testing.
My familiarity with Ruby combined with a Google search led me to the Nestful gem. A few lines of Ruby allowed me to put my API through its paces while supporting authentication and JSON serialization/deserialization with a RESTful wrapper. A gem indeed!
Let’s get to some tangible examples of how this was useful. I’ll start by sharing a minimal/fake server backend in PHP using Toro:
Ok, now that we’ve got all that server stuff out of the way, let’s start writing some tests. If you’re unfamiliar with Toro, then you should become acquainted. If you’ve worked with object-oriented PHP, then will only take a few minutes get up to speed.
Now, once you get the Ruby gem installed (
gem install nestful), you’ll be able to write two simple tests:
To spell it out, both tests are attempting to access endpoints that we have not created. In both of these cases, we expect to receive a 404 error. Now before we start testing the user creation endpoint, let’s define two helper functions:
Here are some pertinent tests that you could write to test the above server:
As you can see from the featured test methods, Ruby’s expressivity coupled with Nestful makes for intuitive integration testing. The above tests should be constructed in a manner non-Rubyists can grok pretty quickly. I’m certainly please with how this turned out and will be sure to use Nestful to continue testing future backends.