Skip to content

Instantly share code, notes, and snippets.

@d11wtq
Created August 18, 2012 05:54
Show Gist options
  • Save d11wtq/3384727 to your computer and use it in GitHub Desktop.
Save d11wtq/3384727 to your computer and use it in GitHub Desktop.
RSpec style let() in Jasmine/Mocha
/**
* Get RSpec-style let() in your Mocha/Jasmine specs.
*/
var let = function (callback) {
var value, called = false;
var memoizer = function() {
if (called) {
return value;
} else {
called = true;
}
return value = callback();
};
afterEach(function() {
value = undefined;
called = false;
});
return memoizer;
};
// example...
describe('Array', function(){
var array = let(function(){ return[]; });
describe('.length', function(){
describe('when empty', function(){
it('is zero', function(){
assert.equal(array().length, 0);
});
});
describe('with two items', function(){
beforeEach(function(){
for (var i = 0; i < 2; ++i) { array()[i] = 'anything'; }
});
it('is two', function(){
assert.equal(array().length, 2);
});
});
});
describe('#push()', function(){
it('appends items to the array', function(){
array().push('bob');
assert.equal(array()[0], 'bob'); // note that the state has been reset
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment