As part of the Test Automation Bazaar minesweeper challenge, a colleague and I developed a CoffeeScript implementation of minesweeper. We wanted to use a test first approach to writing our CoffeeScript, so we decided to use Jasmine.
Setting up a development environment
- Ruby 1.9.2 (specified through a RVM .rvmrc file)
- CoffeeScript installed via Homebrew
- jasmine gem: for writing/running tests
- Sublime Text 2 editor for writing code
Specifying a Guardfile
A Guardfile consists of a bunch of guards that perform actions whenever a file is modified in that location. Our Guardfile looked like:
Writing a Jasmine specification in CoffeeScript
A Jasmine spec in CoffeeScript looked something like this:
describe 'GameState', -> game_state = null field = Field.new mineCount: 1, rows: 1, cols: 3 beforeEach -> game_state = GameState.new field it 'should initialise lost to false', -> expect(game_state.lost()).toEqual false it 'should initialise won to false', -> expect(game_state.won()).toEqual false it 'should initialise remaining_mines to mine_count', -> expect(game_state.remaining_mines()).toEqual 1 it 'should initialise remaining_mines to mine_count', -> expect(game_state.remaining_cells()).toEqual 2
Running Jasmine tests
The jasmine gem makes it very easy to run your jasmine tests. There’s a rake task called ‘jasmine’ which you can run to launch a jasmine server locally on port 8888. If you browse to that page, you’ll see something like this:
Test First CoffeeScript development
Now that you have Jasmine running, and Guard generating the CoffeeScript, it’s easy to write a new spec, refresh the Jasmine browser page to run all your tests (in our case in a third of a second) and then write the code to make it pass.
Automatically running Jasmine tests on Travis CI
If you’ve got your CoffeeScript and Jasmine on github, it’s trivial to automatically run all your Jasmine tests using the Jasmine::Ci rake task on Travis CI. All you need is a .travis.yml file like:
language: ruby rvm: - 1.9.2 env: - DISPLAY=:99.0 before_install: sh -e /etc/init.d/xvfb start
Once you add the project to travis, it’ll automatically run whenever you push. Magic.
- Use Sublime Text 2 for CoffeeScript joy: TextMate 2 forces you to use tabs (4) for CoffeeScript development, we couldn’t find a way to make it stop, and had to switch to Sublime Text 2 (for the better).
- Use the jasmine_content div to test the DOM. Jasmine uses a special div with an id of jasmine_content, which we used to inject and test HTML.
- CoffeeScript classes are odd: we instead used closures to encapsulate state, using a new method on an object, which has the added benefit of looking like ruby.
I hope you enjoy your CoffeeScript test driven development with Jasmine.