Testing javascript in rails applications

Hello everyone, today I brought a text about tests in javascript more specifically with rails. In the past weekend I was researching, the content is scarce but I discover the existence of some gems to facility this process.

Tests are important to increase the software quality, and rails make this relatively easy with rspec, but rspec is only for you back-end. In front-end we need another approach, like jasmine (a framework to test our javascript)

Here I will show to you an explaining to get started with jasmine in rails. Ok, here we go.


  1. Add jasmine-rails to you gemfile;
group :test, :development do
  gem ‘jasmine-rails’

2. Run this command to configure necessary files. To see more, access the oficial repository from this gem.

rails generate jasmine_rails:install

A good thing about this gem is the option to use coffee script. To write tests with coffee script need only to put this configuration in your jasmine.yml.


And here you can see an example from jasmine… Woow it’s looks like rspec? yep, is very similar.

describe(‘Foo’, function() {
it(“does something”, function() {
expect(1 + 1).toBe(2);

Now a example with a real case, I have a side project named classgame and there I’d like try new things. Ok, in that app I need to test a helper that is responsible to toggle a sidebar:

class @Contents
  @menu_toggle_on_load: ->
  if typeof localStorage == ‘undefined’
    console.log ‘Your browser does not support HTML5 localStorage.’
  if localStorage[‘cllps’] == ‘collapse-sidebar’
    $(‘body’).addClass ‘collapse-sidebar’

Here is the test, look the follow ‘before each’ code, he’s similar to our ‘before each’ from rspec, and see that I needed to require my original file, and put my spec on the same path as my javascript file. This is necessary for the test to recognize my JS.

javacript file path: javascripts/helpers/contents_helper.coffee

spec file path: javascript/helpers/contents_helper_spec.coffee

#= require helpers/contents_helper.coffee
describe “ContentsHelper”, ->
  beforeEach = ->
    loadFixtures “contents.html”
  it “should add class collapse-sidebar”, ->
    element = $(“body”)
    window.localStorage[‘cllps’] = ‘collapse-sidebar’
  it “Should not add anything”, ->
    element = $(“body”)
    window.localStorage.removeItem ‘cllps’

note: I use toHaveClass but this is not from jasmine, to use this you will need install jasmine-jquery you can see more in oficial repository

To run the tests you need only to write this in your terminal

rake spec:javascript

Below you can see the results.

That’s it, I hope I have helped you, see you soon.