Jun 22, 2009
Easy Javascript Validation with Javascript Lint For Rails Testing
I found this great Javascript Lint tool. It checks for common(missing semicolons) and not so common(use of the void type) javascript errors. A full featured Selenium test suite would be the ideal for full javascript testing coverage but Javascript Lint is a no hassle addition.
I wrote a simple Rails integration test case to scan all the javascript files in the public/javascripts folder. Download the javascript lint tool and add the file below to your integration test suite. You easily adapt this to Rspec if you would like.
require 'test_helper'
class JavascriptTest < ActionController::IntegrationTest
# Download jsl from http://www.javascriptlint.com and add the jsl to your PATH environment variable
def setup
@js_paths = File.join(Rails.root, 'public', 'javascripts', '*.js')
end
test "validate javascript files for errors" do
Dir[@js_paths].each do |js_path|
output = %x[jsl -process #{js_path}]
is_valid_js_file = output.include?("0 error(s)") ? true : false
assert(is_valid_js_file, "JSLint on #{js_path} should return no errors: \n #{output}")
end
end
end
Here's an example of the error output:
2) Failure:
test_validate_javascript_files_for_errors(JavascriptTest)
[/test/integration/javascript_test.rb:14:in `test_validate_javascript_files_for_errors'
/test/integration/javascript_test.rb:10:in `each'
/test/integration/javascript_test.rb:10:in `test_validate_javascript_files_for_errors']:
JSLint on ..../public/javascripts/application.js should return no errors:
JavaScript Lint 0.3.0 (JavaScript-C 1.5 2004-09-24)
Developed by Matthias Miller (http://www.JavaScriptLint.com)
application.js
.../public/javascripts/application.js(3): lint warning: missing semicolon
num = ;
........^