Testing web services with rspec

Jan 07, 2008

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

Hi, I'm Glenn! 👋 I'm currently Director of Product @ HashiCorp, and we're hiring! If you'd like to come and work with me and help make Terraform Cloud even more amazing we have multiple positions opening in Product ManagementDesign, and Engineering & Engineering Management across a range of levels (i.e., junior through to senior). Please send in an application ASAP so we can get in touch.