By Andreas Fast

If you’re using the Handsoap gem to implement a web service client you may be interested in knowing how to stub the call to the webservice and returning the xml you want. Here is a quick example showing how to do just that.

Let’s dive in!

I used Mocha to stub the methods. But you can use whatever library you like.

When using Handsoap normally you have a class that inherits from Handsoap::Service where you configure the Web Service client.
The aim is to use a xml string to mock the web service’s response.
When we want to call a webservice we use the invoke method supplied by the Handsoap::Service class.

So that method is exactly what we want to stub. That way we make sure we test all our code, not worrying about the gem’s code and of course without actually hitting the remote web service.

The xml string we would like to get as a response might look like this.


You can get this xml string if you print out the response of a webservice call.

Looking for the request call

Digging into the handsoap gem I found that the response object of the Service#invokemethod is the one returned by:

How does parse_http_response work?

Building the response object

If you look at Service#parse_http_response it calls Service#parse_soap_response_document where you can see how it builds the xml object from the raw xml string.
So this is exactly how we will build the response object for our stubbed method, namely:

This is safe to do since we are using Handsoap’s configuration to parse the string and it will work just as if you are using it in production.
Now again in Service#parse_http_response you can see the final line doing:

So when stubbing we need to respond with:

But before that, make sure that if you did override the on_response_document method, you will have to call it explicitly since the parse_http_response won’t be calling it for us:

Finally, we are ready to stub the web service with our xml document:

Bringing it all together

Now, whenever you call invoke on your web service class, it will respond with the xml string you passed in to the XmlQueryFront#parse_string.