Getting Started with Jasmine and Rails 3.2

tldr; check out the git repo

Some good folks have been putting together gems that really help getting started with Javascript testing in Rails, which became somewhat more challenging with the Rails 3.1 asset pipeline.  I decided to dig through some of this and get up to speed with a fresh install of Rails 3.2.2 using my favorite JS testing framework, the BDD-style Jasmine.

I started with Derek Hammer’s testing coffeescript tutorial — I’m not sold on coffeescript, so I reimplemented the first “sanity” spec in plain old javascript.

Note: do not name your .coffee files the same root name as your .js file — only one of them will be executed twice.  Here’s a comparison of the syntax:

Coffeescript Jasmine Spec:

describe "sanity", ->
  it "1 should == 1", ->
    expect(1).toBe(1)
  it "says hello", ->
    expect(helloWorld()).toEqual("Hello!")

Javascript Jasmine Spec:

describe("sanity js", function() {
  it("2 equals 2", function() {
    expect(2).toEqual(2);
  });
  it("says hello", function() {
    expect(helloWorld()).toEqual("Hello!");
  });
});

Ok, I’m almost won over to coffeescript by this example — it’s nice that I can write my specs in coffeescript and code in Javascript (and I assume vice versa), so I can experiment without having to make a binary decision.

I can see failing specs by running rails s and going to http://localhost:3000/jasmine and it looks like this (when I’ve defined the helloWorld() function but it returns the wrong thing):

Even better, using jasmine-guard, I can see this on the command line:

Summary of getting this all working:

Using rails 3.2.2…

$rails new jasminerice-example
$cd jasminerice-example

add the following to your Gemfile

group :development, :test do
  gem "jasminerice"
  gem "guard-jasmine"
end
bundle
brew install phantomjs

I got a “SHA1 mismatch” error, fixed with

  brew update
  brew install phantomjs

Then

bundle exec guard init jasmine
mkdir -p spec/javascripts
touch spec/javascripts/spec.js
touch spec/javascripts/spec.css

in spec/javascripts/spec.js

//= require application
//= require_tree .

in spec/javascripts/spec.css

/*
 *= require application
 */

Now any coffee or js you put in spec/javascripts will be executed when you rails s and go to http://localhost:3000/jasmine or see your specs run on the command line with:

bundle exec guard

Happy Testing!

2 Comments

  1. Posted March 4, 2012 at 9:20 am | Permalink

    I noticed that my keydown tests are failing if i run them with guard - I assume guard is using phantomjs?

  2. Posted March 8, 2012 at 3:05 pm | Permalink

    Yes! Note: I installed it with brew.

Post a Comment

Your email is never shared. Required fields are marked *

*
*