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! 



Thursday, October 9, 2008

Deploying your Webby site

I've been using webby a lot lately.  It's hot for static-like sites.  The site that I've been really digging into Webby with is TheDailyRefactoring.com.

The cool thing about webby is it's capistrano-like deployment.  You can deploy your site after generating it by using the following command:
$ webby deploy
This won't work until after you setup some constants though.  In your "Sitefile" in the root of your webby-application, you need to set the user, host, and directory of where your site is going to be hosted.

# Sitefile
SITE.user = "web"
SITE.host = ""
SITE.remote_dir = "/www/thedailyrefactoring.com"

After that, you can deploy your site immediately! 

Word to the wise, it pays to setup public-key-authentication between your servers to make this process super simple.