Created
September 17, 2010 19:25
-
-
Save diogobaeder/584781 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
A simple helper for cleaning MongoDB collections in NodeJS, using mongoose. | |
They act as setup/teardown cleaners | |
*/ | |
// lib/tools.js | |
exports.chainedCalls = function() { | |
var funcs = Array.prototype.slice.call(arguments, 0); | |
function callNext() { | |
if (funcs.length) { | |
var func = funcs.shift(); | |
func(callNext); | |
} | |
} | |
callNext(); | |
}; | |
// test/tools.js | |
var tools = require('lib/tools'); | |
exports.cleanModelTestCase = function(models, testCase) { | |
if (!Array.isArray(models)) { | |
models = [models]; | |
} | |
if (models.length) { | |
return function(test) { | |
var beforeDrops = [], | |
afterDrops = [], | |
finalCallbacks = []; | |
function accumulateDrops(drops, model, isLast) { | |
drops.push(function(resume){ | |
model._collection.drop(function(){ | |
if (!isLast) { | |
resume(); | |
} | |
else { | |
test.done(); | |
} | |
}); | |
}); | |
} | |
for (var i = -1, len = models.length; ++i < len;) { | |
accumulateDrops(beforeDrops, models[i], false); | |
accumulateDrops(afterDrops, models[i], (i == len - 1)); | |
} | |
function runTestCase(resume) { | |
testCase(test, function(){ | |
resume(); | |
}); | |
} | |
finalCallbacks = finalCallbacks.concat(beforeDrops, [runTestCase], afterDrops); | |
tools.chainedCalls.apply(tools, finalCallbacks); | |
}; | |
} | |
}; | |
// test/unit/model.js | |
exports.testUserLookup = testTools.cleanModelTestCase(User, function(test, done) { | |
test.expect(2); | |
var foo = new User(); | |
foo.username = 'foobaruser'; | |
foo.password = 'foopass'; | |
foo.save(function(){ | |
User.find({username: 'foobaruser'}).one(function(foo2){ | |
var input = 'foopass'; | |
test.equals(foo2.username, 'foobaruser', 'username set'); | |
test.ok(foo2.passwordMatches(input), 'password must match to the user'); | |
test.done(); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment