Wednesday, July 14, 2010

JSpec tests running in CI

A lot of people, myself included, have been TDDing our javascript for awhile but it seems like it's still fairly rare for the tests to be run in the CI build. I've taken some time today to get our existing suite of JSpec tests to run in our CI server (Hudson in our case) and thought I would share what I did. My general approach should be useful regardless of which CI server you are using.

It's actually fairly simple: I'm using the capybara selenium driver to run the JSpec tests and grab the results from the DOM when they finish. Here's the testcase:

I define an array of all my jspec tests, loop over them, munge them into a legal test method name and define a method that delegates to run_jspec. run_spec opens a file url (had to go underneath capy here so its a little icky) and then waits for the .failures div to appear. It should be noted that capybara will wait for an element to appear when you call page.has_css?

From here, running it under CI is trivial. In fact I didn't have to do anything at all, the tests was found by rake test:integrations and ran (and passed!) in the next build. Most of the heavy lifting is done by capybara and selenium-webdriver.

Obviously there is a lot that could be done to improve this code. I could grab the jspec file from a FileList, and grab some better failure messages from the DOM. I could also probably write a custom JSpec formatter to make this easier on myself even. I'm thinking if there is interest I could finish this up and turn it into a gem. Please comment if you'd use such a thing.

Also, one more thing you will need is the JSpec runner file that can run a single test. I did that like so: