My Site

Testing web services with rspec

So you've come over to testing with rspec and it first the bill on most occasions. There are still a few areas though, like decent integration testing, where you still fall back to Test::Unit. So what about testing web services? Sure, ActionWebService is no longer part of rails core but a number of my clients have legacy systems we need to talk to, or 3rd party applications that have been built around SOAP. And at the end of the day, they're still a damn sight better than many of the other alternatives even if it's not part of the new church of REST.

So now it's time to combine the best of the old-school with the best of the new, SOAP meets RSpec

Start with a normal rspec controller spec, with two minor changes. Here's an example from a recent project:

require File.dirname(__FILE__) + '/../spec_helper'
require 'action_web_service/test_invoke'

describe MySOAPController do
  before do
    @account_xml = 
        ... some elements here ...
  it "should parse account xml and return true if successful" do
    result = invoke :AddAccount, @account_xml
    result.should eql(true)
  it "should parse account xml and return false if data is invalid" do
    result = invoke :AddAccount, "no xml here!"
    result.should eql(false)

The only noticeable differences here are that we've got an additional include reference:

require 'action_web_service/test_invoke'

and that rather than raising a get/post/put/delete to retrieve the data, we call invoke against the API and return the result to a local variable to later call assertions on, like so:

result = invoke :AddAccount, @account_xml

The syntax is invoke followed by the method name you wish to call, and then whatever parameters the method is expecting. In this instance it receives an XML string as the only parameter, and is expected to return a boolean response

Glenn Gillen

I'm an advisor to, and investor in, early-stage tech startups. Beyond that I'm an incredibly fortunate husband and father. I'm currently a Product Manager at HashiCorp. Previously at AWS and Heroku.

Working on a developer-facing tool or service? Thinking about starting one? Email me and let me know