Rails Plugin to Validate (X)HTML and CSS

Here is an enahnced version of Scott Raymond’s assert_valid_markup
plugin that I use in my projects. Below are the directions for use;

HowTo Validate (X)HTML

# Calling the assertion with no parameters validates 
# whatever is in @request.body, which is automatically 
# set by the existing get/post/etc helpers. For example:

class FooControllerTest < Test::Unit::TestCase
  def test_bar_markup
    get :bar
    assert_valid_markup
  end
end

# Add a string parameter to the assertion to validate 
# any random fragment. For example:

class FooControllerTest < Test::Unit::TestCase
  def test_bar_markup
    assert_valid_markup "<div>Hello, world.</div>"
  end
end

# For the ultimate in convenience, use the class-level
# method to validate a number of actions in one line. 

class FooControllerTest < Test::Unit::TestCase
  assert_valid_markup :bar, :baz, :qux
end

HowTo Validate CSS

# Pass a string parameter to the assertion to validate 
# a css fragment. For example:

class FooControllerTest < Test::Unit::TestCase
  def test_bar_css
    filename = "#{RAILS_ROOT}/public/stylesheets/bar.css"
    assert_valid_css(File.open(filename ,'rb').read)
  end
end

# For the ultimate in convenience, use the class-level
# method to validate a bunch of css files in one line.
# Assumes that the CSS files are relative to 
# $RAILS_ROOT/public/stylesheets/ and end with '.css'. 
# The following example validates 
#  $RAILS_ROOT/public/stylesheets/layout.css, 
#  $RAILS_ROOT/public/stylesheets/standard.css and 
#  $RAILS_ROOT/public/stylesheets/theme.css

class FooControllerTest < Test::Unit::TestCase
  assert_valid_css_files 'layout', 'standard', 'theme'
end

Most of the credit for this plugin goes to Scott for the initial idea! The modifications that I made include;

  • Validation of CSS files.
  • Caching of fragments occurs in $RAILS_ROOT/tmp according to the name of the test class + test method. This avoids filling up the system temp folder with expired cache files.
  • Ability to turn off validation by setting the “NONET” environment variable to “true”.

Update 12th of May, 2010

The plugin is now available on GitHub. See the GitHub project page