15 6 / 2012
Testing API from Rails Console
Recently I created small API for one of my apps that is to be accessed by an iPhone application. I followed Railscasts guides on how to create, version, and secure it with access token. Even though you can test the api with CURL command, it tend to get a bit more complex when you need to specify token header every single time.
I wanted to be able to test the API in more simplistic way. I wanted it to be something like this:
api User.first, :get, '/api/projects'
Here is the simple helper method that can make this process much easier:
def api(user, method, url, params=nil)
headers = {
'Accept' => 'application/roommates.v1',
'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Token.encode_credentials(user.api_token)
}
app.send(:"#{method}", url, params, headers)
ap JSON.parse(app.response.body)
end
Method simply sets proper headers, issues request, pretty-prints returned json (with awesome_print gem), and returns it. You can customize any way you want.. this is just an idea of how it might look.
All you have to do is put this method in .irbrc file in your project root and it will be automatically loaded each time you start your rails console.