ActiveResource::HttpMock doesn’t mock hard enough
I’ve got a family of (ARes) resources that are available through an external web service. These resources are used pervasively throughout my site -they appear on about 75% of my site’s pages. When testing, of course I don’t want to hit the web service and endure the vagaries of performance and availability. The nice people developing ActiveResource seem to have accommodated this desire by providing the HttpMock class.
But… HttpMock is very exacting in its demands for matching requests -it’s all or nothing. That means that if I make fifty different requests, all identical save for a tiny change in the URL params, I need to make fifty different mocks. Ouch.
So I decided to mock the mocker. No, really. Using mocha, I mock the HttpMock::Request#== method to always return true. Now, regardless of the request path, HttpMock always sees a match and returns my mock data.
The denouement, using the Rails docs as a starting point:
def setup
@matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
ActiveResource::HttpMock.respond_to do |mock|
mock.post "/people.xml", {}, @matz, 201, "Location" => "/people/1.xml"
mock.get "/people/1.xml", {}, @matz
mock.put "/people/1.xml", {}, nil, 204
mock.delete "/people/1.xml", {}, nil, 200
req_res = mock.get "/", {}, "Constant Data Goes Here", 200
req_res.last.first.stubs(:==).returns(true)
end
end