I’m trying to test some backbone.js views using Jasmine (via jasmine-headless-webkit). Everything is working well, except that my haml-js templates aren’t accessible under test.
The following code in my view works fine:
render: =>
html = JST['views/avia_view_template']()
$(@el).html(html)
… but when it’s run as part of a Jasmine spec I get the following failure:
ReferenceError: Can't find variable: JST in /home/duncan/avia/app/assets/javascripts/views/avia_view.js.coffee
I suspect I’m doing something wrong in jasmine.yml. I’ve explicitly included the template file it still fails:
src_files:
- "vendor/**/*.{js,coffee}"
- "lib/**/*.{js,coffee}"
- app/assets/javascripts/application.js
- app/assets/javascripts/avia.js
- app/assets/javascripts/jquery-1.6.4.js
- app/assets/javascripts/underscore.js
- app/assets/javascripts/backbone.js
- app/assets/javascripts/jquery.jqGrid.min.js
- app/assets/javascripts/views/avia_view_template.jst.hamljs
- app/assets/javascripts/views/avia_view.js.coffee
Perhaps I’m just taking the wrong approach here … should I be using Jasmine to stub & mock out the calls to JST and jQuery? A strictly unit-testing approach says I should, in which case the lack of template access is a non-issue.
Any tips – either on my approach to testing, or the specific JST failure, would be greatly appreciated.
No need to stub, you just need to set up your asset paths correctly. In order to take advantage of the Sprockets integration in 0.8.0 and above, the best way to set up your jasmine.yml file would be like this:
This will set up Sprockets to look in
app/assets/javascriptsandlib/assets/javascripts, and will tell jasmine-headless-webkit to pull every possible file in both directories. Jasmine’s normal file requiring wouldn’t be used in this case, just Sprockets.Then, set up your
requirestatements like you would normally in your JS files. So in ‘application.js.coffee’:And in
avia_view.js.coffee:Of course, those
.hamljstemplates won’t get loaded unless a Sprockets-capable Haml processor has been loaded. So you would want to have a Gemfile that had at least this in it:Then, if your application itself knows what to do when those vendored JS gems are loaded, you could get rid of you own copies of jQuery and Backbone, and you’d also have
.hamljstemplates available. At that point, you should run using Bundler:Last thing, the best way to make sure everything’s actually getting loaded is to use the list option:
That will run everything through JHW’s and Sprockets’ file loaders and print out the order of files to be included. This will help diagnose
requireproblems, since you always have to deal with both Jasmine-style and Sprockets-style loading in a single scenario. Setting up your src files to be loaded entirely via Sprockets simplifies the process a lot, so I would recommend a setup a lot like this one.