In a recent project I needed a way to fake a response from a server in my Cucumber features. Specifically, I was testing integration with a payment gateway and wanted to stub it’s responses based on different requests.
In the past I have used FakeWeb, however it becomes a little hairy when you need to stub a response based on request body. I came across a couple of alternatives, firstly WebMock which looks promising but then Artifice from the mighty Yehuda Katz caught my eye…
Artifice lets you “replace the Net::HTTP subsystem of Ruby with an equivalent that routes all requests to a Rack application”. I like the simplicity of this solution as you can in essence use a Rack application to replace the responses of the service you are testing.
An Example
First we create a simple Rack application to stand in for the server we are interacting with.
app = proc do |env|
[200, { "Content-Type" => "text/html" },
["Hello world: #{env.inspect}"]
]
end
Then we simply use Artifice’s “activate_with” method to wrap any requests.
Artifice.activate_with(app) do
response = Net::HTTP.start("google.com") do |http|
http.post("/the_url", "foo=bar")
end
puts response.body
end
This allows for a Rack app to be used as a stand in for a complete API, it could be a Sinatra app for example allowing for easy route handling. We could go so far as to have a series of Rack apps that can be used as stand-ins for common API’s.