Open-uri makes tests easy
Eric Hodel | Mon, 21 Nov 2005 01:28:00 GMT
Neither of the two Ruby Flickr APIs do what I want. One stomps all over the global namespace (Photo will be a model class, it adds a Photo class at the toplevel) and doesn’t have the photo taken date as one of its properties. The other doesn’t support the search method (you get back an XML blob instead of a collection) or the photo taken date.
Neither has tests, so I wasn’t going to figure out how to add what I wanted to either. Instead, I decided to wrap as much of the API as I needed with something that I could test.
On a whim, I decided to use open-uri instead of Net::HTTP. This made testing super-easy. I don’t have to touch the network at all, other than to get a blob of XML to feed into the test:
class Flickr
attr_accessor :responses, :uris
def open(uri)
@uris << uri
yield StringIO.new(@responses.shift)
end
end
class FlickrTest < Test::Unit::TestCase
def setup
@flickr = Flickr.new 'API_KEY'
@flickr.responses = []
@flickr.uris = []
end
Then a test simply adds the XML blobs it is supposed to receive from flickr up-front. After performing the request, I assert it attempted to fetch the correct URLs along with the rest of the stuff the method was supposed to do. (Search is paginated, and I wanted to fetch all the photos without making things clumsy for the user.)
def test_photo_get_info
@flickr.responses << <<-EOF
...
EOF
info = @flickr.photo_get_info :photo_id => 59864477
assert_equal 1, @flickr.uris.length
assert_equal 'http://flickr.com/services/rest/...',
@flickr.uris.first
assert_equal Time.at(1131153707), info[:date_taken]
assert_equal Time.at(1131153708), info[:date_uploaded]
end
Comments are disabled

Articles