Skip to content

Instantly share code, notes, and snippets.

@pacovell
Created October 25, 2011 02:54
Show Gist options
  • Save pacovell/1311173 to your computer and use it in GitHub Desktop.
Save pacovell/1311173 to your computer and use it in GitHub Desktop.
Controller test harness for dispatch
/**
Done. Simulated control chain for testing controllers with Vows
Copyright (c) 2011 Done. Corporation
*/
var http = require('http'),
controllers = require(process.cwd() + '/lib/controllers');
var ControlChain = module.exports = function (controllerName) {
this.router = controllers.router;
this.controller = controllers[controllerName];
if (!this.controller) {
throw new Error('Could not find controller ' + controllerName + '. Giving up.');
}
};
// simulate a get request on the given action
// @options options for the action (optional)
// session - hash to be added to the session via _.extend()
// request - hash to be added directly to the request via _.extend()
// query, body - hash of simulated incoming parameters
// format - request format; 'html' if not included
// @process - setup functions (optional)
// before - functions to run before this request, for example mocking setup
ControlChain.prototype.get = ControlChain.prototype.post =
ControlChain.prototype.put = ControlChain.prototype.delete = function (action, options, process) {
var chain = this,
options = options || {},
process = process || {};
return function () {
var callback = this.callback;
// Patch request
var request = new http.IncomingMessage();
request = _.extend(request, options.request || {});
request.session = options.session || {};
request.query = options.query || {};
request.body = options.body || {};
request.format = options.format || 'html';
request.action = action;
request.routes = chain.router.path;
// Patch response
var response = new http.OutgoingMessage();
response.end = function (body) {
if (_.isUndefined(response.statusCode)) {
response.statusCode = 200;
}
response.body = body;
callback(null, request, response);
};
var next = this.next = function (err) {
callback(err);
};
// Run any before options, useful for setting up mocks, etc
if (process.before) {
if (process.before instanceof Array) {
_.each(process.before, function (fn) {
fn();
});
} else {
process.before();
}
}
chain.controller.addRequest(request, response, next);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment