Fool’s gold

Leave a comment

December 18, 2012 by Rob Nichols

I hate JavaScript, but I love what you can do with it. Taming it is a necessary evil, if you want to provide web users with the best interface available. So being able to reliably test JavaScript code is a real boon.

I have started to use Jasmine to provide a JavaScript test environment, and I have to admit that I like it a lot.

I added jasmine to my rails app by adding this to my Gemfile:

gem 'jasmine', :group => [:development, :test]

That adds Pivotal’s ruby plugin to the app. Setting it up is described here.

With that in place, I could start adding tests to my app via /spec/javascripts. Note that the test file name needs to end ‘_spec.js’.

The tests themselves are JavaScript files. The syntax is quite like rspec (which is a not a plus point in my book as I am not a fan of rspec, but I can live with it):

describe("A suite", function() {
it("contains spec with an expectation", function() {

Note that .toBe is acting on expect, and not the item being tested, so none of the rspec monkey patching issues.

To run the tests, the jasmine gem adds a rake task:

rake jasmine

Running that starts a server on port 8888 (I get a warning ‘WARN TCPServer Error: Address already in use – bind(2)‘ but everything works as it should. The warning appears whichever port I use for the server. I think the server is seeing itself and erroneously issuing the warning.).

Pointing a browser at localhost:8888 then displays the test output.

I found using fixtures was useful. Jasmine fixtures are html pages that you can create with the elements you want your JavaScript to act upon. Which means you can test functionality in isolation and be more sure of what is being tested. To add fixtures, jquery support needs to be added to jasmine. I used a technique described in a RailsCast, to install it. I’d recommend watching the RailsCast even if you don’t want to use fixtures, as it is a nice demonstration of using Jasmine with Rails.

You can see my first Jasmine test here. Now I have a decent test environment, I am a little more confident that the JavaScript in my app is behaving the way I intend it to.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: