Mocking GeoKit's Geocoder

I’ve been using GeoKit a lot in Rails, most often for geocoding. Models like Points, Companies and Users usually have an address, city, state, postal code and country - which might need to be geocoded so we can place them on a map, or check distances.

It’s definitely bad to let geocoder calls happen in tests. Not only does it slow things down, but if for some reason your network is not so good, tests will fail unexpectedly. Here are the helpers I like to use when writing the tests. This is using Test::Unit and Mocha:

In use, it’s pretty straightforward. You either expect the geocoder to succeed (a certain number of times), fail, or not be used at all. That last point is important because it’s easy to forget and have a model that geocodes on every save (via a before_save callback, for instance). That will slow down site response time because of the network delays.

Finally, here are some generic examples of each of the test helper methods in use: