Javascript Testing in the Asset Pipeline with Rails 3.1

tl;dr: Check out test_track!

Now that Rails 3.1.0 has been officially released, its time to get serious about leveraging some of its new features. We spend a lot of time writing rich web clients in Javascript and the amount of test coverage we have for that code has drastically increased in 2011. Here's how we're using the new features in 3.1 to make testing Javascript easier.

The Asset Pipeline is perhaps the most interesting feature included in the 3.1 release, and it was the one we were most excited to get to use. If you're not familiar with the Asset Pipeline, it's a new system for organizing, compiling and compressing Javascript and stylesheets. Under the hood it's leveraging Sprockets 2 and Tilt to give developers a powerful and easy to use system for compiling assets in a variety of formats.

How To Test from within the Pipeline

With a mind for testing, we approached the asset pipeline with caution. Sure, concat'ing and compiling all of our front end code is great, but how can it be integrated with a test suite?

We use Jasmine and Qunit for testing Javascript, and while Jasmine has good ruby integration it felt a bit ham-fisted when compared to what the asset pipeline can do for us. After experimenting with mountable engines and making gems interact with the Sprockets environment Rails exposes, we found a solution to our problems.

test_track is a gem that creates a mountable engine for Javascript test runners. It currently supports Qunit and Jasmine, but there's room for any other front end testing framework.

It works by appending some default locations into an application's asset_path and creating routes that include the test runner html and Javascript. Your application's code and tests also get included on those pages, with no additional overhead for the developer.

Working with test_track

Once the test_track gem is added to your project, you just need to create a test manifest in spec/javascripts or test/javascripts that includes require statements for any test files. Here's what a sample test manifest would look like:

// SUITE :: Jasmine
// SUITE MANIFEST :: spec/javascripts/jasmine.js
// TEST SRC DIR :: spec/javascripts
//= require helpers/spec_helper
//= require profile_spec
//= require user_spec

With that in place, all you need to do is mount the engine in config/routes.rb:

mount TestTrack::Engine => 'test'

And now you can run your Jasmine and Qunit tests at '/test/jasmine' and '/test/qunit'.

test_track is available as gem, so to include it in your project, just add

gem "test_track"

to your project's Gemfile and you're off to the races! You can checkout test_track on GitHub.