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 ...
EOF
end
it "should parse account xml and return true if successful" do
User.should_receive(:create)
result = invoke :AddAccount, @account_xml
result.should eql(true)
end
it "should parse account xml and return false if data is invalid" do
User.should_not_receive(:create)
result = invoke :AddAccount, "no xml here!"
result.should eql(false)
end
end
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
Previously I led the Terraform product team @ HashiCorp, where we launched Terraform Cloud and set the stage for a successful IPO. Prior to that I was part of the Startup Team @ AWS, and earlier still an early employee @ Heroku. I've also invested in a couple of dozen early stage startups.