Scott Raymond
home
20 Sep 2005
I’ve always wanted an automated way to validate my Rails project’s (X)HTML output. In July, the W3C Validator made it easy, by allowing fragments to be POSTed to their service. Now, with a simple custom assertion, your functional tests can ensure your markup is valid, and that it stays valid.
Just add this to your test/test_helper.rb:
<pre> def assert_valid_markup(markup=@response.body)
require 'net/http'
response = Net::HTTP.start('validator.w3.org') do |w3c|
query = 'fragment=' + CGI.escape(markup) + '&output=xml'
w3c.post2('/check', query)
end
assert_equal 'Valid', response['x-w3c-validator-status']
end
And then (given an action called ‘home’) call the assertion from your functional tests like so:
<pre> def test_home
get :home
assert_valid_markup
end</pre>
And presto, your markup will be validated every time you run your tests, and if something happens to invalidate your output, you’ll know it right away.
By default, assert_valid_markup() will validate the contents of @response.body (which is set by the get line); you can also pass it an argument to check something else. If you want more detail on the validation errors, modify the assertion to look into response.body — it’s an XML file with helpful information about each error.