Dec 01 2011

Testing a REST Web Service with Cucumber

TDD Github API | comments

The Cucumber book has been helpful in a way that I saw more options for testing a web service. It's my first time to use HTTParty. In the past, I always used RESTClient gem for this kind of task.

Just think the example is overkill. Maybe we just want to know whether the JSON response includes the data we expect.

So this helps:

              features/step_definitions/rest_steps.rb
              
              require 'httparty'
              
              When /^the client requests GET (.*)$/ do |path|
                @last_response = HTTParty.get('http://somewebsiteidontknow.com' + path)
              end
              
              
              Then /^the JSON response should include "([^\"]*)"$/ do |response|
                JSON.parse(@last_response.body).to_s.should match response
              end
              
              Then /^the JSON response should not include "([^\"]*)"$/ do |response|
                JSON.parse(@last_response.body).to_s.should_not match response
              end
              
              @people-api
              
              Scenario: GET People
                When the client requests GET /api/v1/people.json
                Then the JSON response should include "A Name"
                And the JSON response should not include "A Mouse"
              

Probably a bad way of testing is just testing whether the response is not nil.

A better example:

              
              When /^ I GET Github (.*)$/ do |path|
                @last_response = HTTParty.get('http://github.com/api/v2/json' + path)
              end
              
              

              Scenario: SEARCH Github user
                When I GET Github /user/search/bridgeutopia
                Then the JSON response should include "bridgeutopia"
                And the JSON response should not include "something"