I recently wanted to create automated testing for coffeescript code in Rails 3.1, including some async (ajax) code. I had to dig around quite a lot, so I’m writing here what I ended up doing for future reference for myself and others who might need it.
You can integrate Jasmin in Rails 3.1 yourself just using the Jasmine gem, but to simplify things with Coffeescript I decided to use a specific gem for the latest version of Rails and its assets pipeline. I couldn’t really choose between test_track and jasminerice, which are both very young, so I went with the first one just based on intuition. Using the other one shouldn’t be very different.
So, I added to my gemfile:
gem "jasmine" gem "test_track"
and installed the new gems with “bundle”
JsonDataSpec is the coffeescript spec file that I was going to create and that will be executed in the test. See the following example
describe "JsonData", -> it 'should should have the correct format', -> answer = null $.getJSON( "/controller/get_my_data/", (data) -> answer = data ) waitsFor -> answer runs -> expect(typeof answer.string).toEqual('string') expect(typeof answer.number).toEqual('number')
The secret here is waitsFor -> answer, which will wait until the answer variable gets a non null value – that is, when the ajax call is complete. Only after that the actual test is run.
Last thing, I configured the test_track engine adding this code to routes.rb:
mount TestTrack::Engine => "test"
And that’s it! To use my tests, I just run the server using rails s and access the tests opening http://localhost:3000/test/jasmine in the browser. Smooth and easy.