Easy Markup Validation
Jun 12, 2009 @ 5:24 pmI wanted a test helper that would assert that my XHTML was valid XHTML. So I wrote one and called it “markup_validity”. You can use it too, and I will show you how.
First, install the gem:
Then, use it in your tests:
require 'test/unit'
require 'rubygems'
require 'markup_validity'
class ValidHTML < Test::Unit::TestCase
def test_i_can_has_valid_xhtml
assert_xhtml_transitional xhtml_document
end
end
Oh. You use RSpec? It supports that too:
require 'rubygems'
require 'markup_validity'
describe "my XHTML document" do
it "can has transitional xhtml" do
xhtml_document.should be_xhtml_transitional
end
end
Debugging invalid markup can be a pain. MarkupValidity tries to give you helpful errors to make your life easier. Say you have an invalid piece of XHTML like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<p>
<p>
Hello
</p>
</p>
</body>
</html>
The error output from MarkupValidity will be this:
.Error on line: 2:
Element 'head': Missing child element(s). Expected is one of ( script, style, meta, link, object, isindex, title, base ).
1: <html xmlns="http://www.w3.org/1999/xhtml">
2: <head>
3: </head>
4: <body>
5: <p>
Error on line: 6:
Element 'p': This element is not expected. Expected is one of ( a, br, span, bdo, object, applet, img, map, iframe, tt ).
5: <p>
6: <p>
7: Hello
8: </p>
9: </p>
MarkupValidity provides a few assertions for test/unit:
The methods provided for RSpec are quite similar:
MarkupValidity even works well with rails. Here is an example rails controller test:
require 'test_helper'
require 'markup_validity'
class AwesomeControllerTest < ActionController::TestCase
test "valid markup" do
get :new
assert_xhtml_transitional @response.body
end
end