I have a very simple xml API for adding users to our system at work. It adds a user to our front end database, and also adds that same user to our back end billing system. It needs a refactor quite badly, so testing needs to be created to make sure that the refactor works as it should.
The xml that it accepts looks like this:
It gets submitted to the api controller of my rails app, using the index action. Here is what it returned when it’s successful:
Because I generated the api_controller, it provided me with a proper functional test. This is where we’ll test the api.
To start, lets put together a simple static test:
Obviously, not the complete file, just the bits I created. The generator script started me off with much more.
If I test this script:
Obviously, the puts statement is not that useful. Let’s replace it with a test:
This will tell us if the api doesn’t return a valid activation code.
Next we need to get rid of that static xml and build it on the fly from some fixtures. I’d like to be able to test a large number of scenarios that might happen, including failures and malicious usage.
Here’s what my yaml file looks like:
To read this in, I’ll create a method in test_helper.rb:
Then, back in api_controller_test.rb, we can call the helper app for each user we find in the yaml file. Make sure that you are requiring the yaml library.
Here’s the loop to read in users from the yaml and test them:
Now our output is:
We can then create multiple yaml files, each containing users that will test the api in one way or another. One might make sure that vendors with invalid usernames or passwords can’t log in. Another might try to use sql injection to trash the database. Use your imagination.