Peter Marklund

Peter Marklund's Home

Mon Mar 23 2009 14:29:04 GMT+0000 (Coordinated Universal Time)

Rails Tip: JavaScript Validation and Testing

JavaScript test coverage is pretty non-existant in most Rails projects and if your application has a lot of JavaScript code this can become a real problem. But it doesn't have to be that way. One thing you can do just to get some basic syntax and style checking of your JavaScript code is to run it through JavaScript Lint. I've added a simple rake task to run all javascript files through the validator:

namespace :test do
  namespace :javascripts do
    desc "Validate all javascript files with javascript lint - assumes jsl on the command line"
    # Visit http://www.javascriptlint.com to download and install the jsl command line tool
    task :validate do
      total_errors = 0
      Dir[File.join(File.dirname(__FILE__), "..", "..", "public", "javascripts", "*.js")].each do |file_path|
        print "#{file_path} ... "
        result = `jsl -process #{file_path}`
        n_errors, n_warnings = result.match(/(\d+) error\(s\), (\d+) warning\(s\)$/).to_a[1, 2].map(&:to_i)
        
        if n_errors > 0
          puts "FAILED"
          puts result
        else
          puts "OK (#{n_warnings} warnings)"
        end
        total_errors += n_errors
      end

      print "TEST RESULT: "
      if total_errors > 0
        puts "FAILURE - #{total_errors} errors"
      else
        puts "OK"
      end
    end
  end
end

In addition to syntax checking I recommend trying out Dr Nic's javascript_test plugin. To get it to work with the latest prototype I had to download JsUnitTest and use that instead of unittest.js.