Friday, October 24, 2008

FakeWeb; the most awesomest for stubbing HTTP content

On my new open-source project TwitterCompare I wanted to have a better way of receiving JSON data in my tests when using HTTParty.

The following calling is to verify credentials against the Twitter API using HTTparty:

get('/account/verify_credentials.json')


The get() makes a call to Net::HTTP.request. However, I don't want to request data from Twitter in my tests since I'll be running them quite frequently and it's a waste of resources to contact their servers, wait a few seconds, receive some data, and then all my tests finish 5 seconds later as well as data that may change.

The FakeWeb fork by Chris Kampmeier is what I used and it is awesome. It will:
  • Intercept calls to Net::HTTP.request
  • Check to see if the requested URL is one that needs to return test data
  • Returns test data
The interception is automatic once you require the following libraries in your spec_helper.rb:
# spec/spec_helper

require 'fake_web'
require 'open-uri'

To setup which URLs you want to be recognized and stubbed during your tests with FakeWeb do the following in your tests wherever you wish:
FakeWeb.register_uri('http://twitter.com:80/account/verify_credentials.json?', :response => '/testfiles/http_responses/verifiy.response.json.txt')
You can pass :response a string that is a path to a file to return that file or you can have it return a string.

NOTICE: The port specification in the register_uri() call.  You need to include the port for the FakeWeb.registered_uri?(url) to return TRUE on an exact match.

And that's it! 



0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home