Peter Marklund

Peter Marklund's Home


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 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
          puts "OK (#{n_warnings} warnings)"
        total_errors += n_errors

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

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.

3 comment(s)


Rasmus Rønn Nielsen said 2009-11-04 13:56:

Thanks Peter. You can use the following the line if you, like me, want to test all js files in subdirectories of the javascripts dir: [...] Dir[File.join(RAILS_ROOT, 'public', 'javascripts', '**', '*.js')].each do |file_path| [...]

Jerry said 2009-10-07 18:10:

For those looking for ways to install jsl, here is the link:

Peter Boling said 2009-04-14 03:36:

Awesome! Jsl was not easy to install... but eventually I got it working! Thanks for this rake task!