Wed, 16 Jan 08

Testing my mod_rewrite configuration with ruby

In order to ensure that I didn’t break anything while setting up my mod_rewrite rules I created a little ruby script to test my expectations. I’ve cut down the rules in the example below but you should get the idea. It’d be quite cool to create a little dsl to better express the intentions of the code.

require 'net/http'

expectations = {
  # Redirect www. to .
  'http://www.the-local-paper.co.uk/' => {
    :url => 'http://the-local-paper.co.uk/', :code => '301'
  },
  # Requests for the-local-paper.co.uk should return a 200 (OK) response
  'http://the-local-paper.co.uk/' => {
    :code => '200'
  }
}

expectations.each do |request_url, expected_attributes|
  puts "Requesting: #{request_url}"

  url = URI.parse(request_url)
  request = Net::HTTP::Get.new(url.path)
  response = Net::HTTP.start(url.host, url.port) do |http|
    http.request(request)
  end

  if redirection_url = expected_attributes[:url]
    raise "Expected '#{redirection_url}' in the Location header but got '#{response['Location']}'." unless redirection_url == response['Location']
  end
  if status_code = expected_attributes[:code]
    raise "Expected status code of (#{status_code}) but got (#{response.code})." unless status_code == response.code
  end
end