Peter Marklund

Peter Marklund's Home

Mon March 23, 2009
Programming

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.

Comments

Peter Boling said over 5 years ago:

Awesome! Jsl was not easy to install... but eventually I got it working!

Thanks for this rake task!

--------------------------------------------------------------------------------

Jerry said over 4 years ago:

For those looking for ways to install jsl, here is the link:
http://www.javascriptlint.com/download.htm

--------------------------------------------------------------------------------

Rasmus Rønn Nielsen said over 4 years ago:

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|
[...]

--------------------------------------------------------------------------------