Posted on June 12, 2013
- Readable — readable tests act as an enforced requirements document as you add team members or return to code long after you’ve written it.
- Writable — writable tests empower you to actually grow your test suite as your source grows.
- Fast — fast tests increase developer productivity.
The first two requirements are easily satisfied using Jasmine. I compared Jasmine and QUnit, and Jasmine wins out for the natural readability of it’s assertions. Side-by-side with Rspec, Jasmine feels like a consistent test suite for our application.
Karma is distributed using Node and npm. Utilize Homebrew to make this step simple.
brew install node npm install -g karma
karma start to check if Karma successfully installed. If it didn’t, check your
PATH and the usual unixy stuff.
Karma ships with a nice helper for generating a configuration file. But before you generate it, you’ll want to create a little structure for your tests.
We created the following folders:
This is all a matter of preference, but having all our files live under spec folder makes sense for us.
spec/karma/config/ will hold our Karma configuration files
You can now generate your configuration using Karma’s init helper:
karma init spec/karma/config/unit.js
You’ll get all the standard fare here. Karma has great documentation for their configuration file. If you want to get up and running with Karma, it is worth your time to see all the options available. A basic file will look something like this.
Go ahead and create a dummy test file to run and see things are working.
Run your tests using
karma start spec/karma/config/unit.js. Assuming you’re serving up your Rails app using pow at
http://railsapp.dev, this works as expected. You can edit
For TDD, we also want tests to run when source files in
files configuration to load
Bridging the Gap
Taking a closer look at the Karma file configuration docs, a solution to get things talking is pretty simple.
We add a pattern for files that are not loaded into the test suite, but are watched for changes to re-run the tests. With this addition, now whenever something in
Right now all the tests are super fast, running in under half a second. As the test suite grows, we’ll want to put more logic around matching source files to test files so we can run only those tests related to what we’re editing for fast TDD.