Skip to content

Instantly share code, notes, and snippets.

@logan-pugh
Last active August 29, 2015 14:05
Show Gist options
  • Save logan-pugh/abd9bed7b97870d10560 to your computer and use it in GitHub Desktop.
Save logan-pugh/abd9bed7b97870d10560 to your computer and use it in GitHub Desktop.
Sails.js testing setup
/*
* Location: /test/helpers/appHelper.js
*
* @description :: Provides 'lift' and 'lower' methods to set up
* and tear down a Sails instance (for use in tests)
*/
var Sails = require('sails/lib/app'),
async = require('async'),
lifted = false,
sailsprocess;
var appHelper = {
/* Starts the Sails server, or if already started, stops and then starts it
*
* @param {function} done Callback function
*/
lift: function (done) {
async.waterfall(
[
// Check whether the Sails server is already running, and stop it if so
function (cb) {
if (lifted) {
return appHelper.lower(cb);
}
cb();
},
// Start the Sails server
function (cb) {
Sails().lift({
log: {
level: 'warn'
},
loadHooks: [
'blueprints',
'controllers',
'http',
'moduleloader',
'orm',
'policies',
'request',
'responses',
'session',
'userconfig',
'views'
],
models: {
// Use in-memory database for tests
connection: 'inMemoryDb',
migrate: 'drop'
},
liftTimeout: 10000
}, function (err, app) {
if (err) {
return cb(err);
}
lifted = true;
sailsprocess = app;
cb(null, app);
});
}
], done);
},
/* Stops the Sails server
*
* @param {function} done Callback function
*/
lower: function (done) {
sailsprocess.lower(function (err) {
lifted = false;
done(err);
});
},
module.exports = appHelper;
/*
* Location: /test/index.spec.js
*
* @description :: This file is run before all other tests.
*/
var appHelper = require('./helpers/appHelper');
before(function (done) {
appHelper.lift(done);
});
// Maybe add another `before` here to load fixtures, or do it in individual tests
after(function (done) {
appHelper.lower(done);
});
/**
* Location: /test/controllers/UserController.spec.js
*
* @description :: Tests the UserController
*/
var request = require('supertest'),
appHelper = require('../helpers/appHelper'),
userFixtures = require('../fixtures/users');
describe('UserController', function () {
before(function (done) {
User.create(userFixtures[0], done);
});
after(function (done) {
// Restart the server to get back to a clean state
// (could just delete the user in this case, but sometimes this is easier)
appHelper.lift(done);
})
describe('#findOneById', function (done) {
it('should get the user', function (done) {
request
.get('/user/1')
.expect(200, done);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment