Tim Riley

Testing for elements in ActiveRecord's XML output

April 18th 2008

Following on from my previous post about customising ActiveRecord’s to_xml output, I have had to write specs to make sure a custom attribute I have added to a model’s XML serialisation actually appears as expected.

ActiveSupport’s Hash.from_xml class method makes this a piece of cake. Instead of testing against the XML as a string or parsing it manually, you can turn it into a hash and get directly to the attribute you want. Behold:

describe Product do
  before(:each) do
    @product = Product.new
  end

  # net_price is the custom attribute I have added to the XML serialisation
  it "should include net price in XML serialisation" do
    @product.attributes = valid_product_attributes
    Hash.from_xml(@product.to_xml)['product']['net_price'].should == @product.net_price
  end
end
Tim Riley

Hi, I'm Tim Riley. I'm a web developer based in Canberra, Australia, where I work at a small design studio called Icelab. This is my blog, where I can share with you the things I learn as I go about building products for the web.

What I Build

Recent Presentations

  1. Facebook Authentication with OAuth
  2. JavaScript Testing with Capybara and Cucumber
  3. Using Titanium to Build Mobile Apps with JavaScript (audio)
  4. An Introduction to Sinatra
  5. Building your Capistrano Recipe Book