Skip to content

RequireJS with Teaspoon

Harry Moreno edited this page Mar 9, 2015 · 8 revisions

If you're using RequireJS and want full integration with Teaspoon you can simply tell it to use the RequireJS boot partial for your suite.

spec/teaspoon_env.rb

config.suite do |suite|
  suite.boot_partial = "boot_require_js"
end

This embeds a require configuration and a require callback to load all the specs that need to be run.

Now, in your spec helper you'll need to include the require.js library that you use. Teaspoon doesn't ship with it.

spec/javascripts/spec_helper.js

//= require require

If you place require.js under the support directory, as suggested, you'll do

//= require support/require

If you're have, and have configured requirejs-rails, this configuration will be used.

The following is an example of what happens behind the scenes in the RequireJS boot partial.

require.config({
  paths: {baseUrl: '/assets'}
});

require(['SomeModel_spec.js'] , function () {
  Teaspoon.execute();
});

If you're running with Code Coverage the RequireJS boot partial will add two extra options to the configuration:

require.config({
  paths: {baseUrl: '/assets', urlArgs: 'instrument=1', waitSeconds: 0}
});

This ensures all files loaded through RequireJS are flagged for instrumentation and disables timeout errors which the files are loaded.

Writing your specs

In your specs, you can now require other assets. If you have custom paths setup in a require config, you may need to include that using sprockets in your spec helper.

SomeModel_spec.js

define(['SomeModel'] , function (SomeModel) {
  describe('SomeModel' , function () {
    // ADD YOUR SPEC
  });
});

Shared behaviors

If you have any shared behaviors you'd like to require, for instance in the directory specs/javascripts/behaviors, it would look like so:

SomeModel_spec.js

define(['SomeModel' , 'behaviors/SharedModel_behavior'] , function (SomeModel , SharedModel_behavior) {
  describe('SomeModel' , function () {
    SharedModel_behavior();
  });
});