Skip to content

Instantly share code, notes, and snippets.

@trinonsense
Forked from damncabbage/factories.js
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trinonsense/9219151 to your computer and use it in GitHub Desktop.
Save trinonsense/9219151 to your computer and use it in GitHub Desktop.
/*
* Set up factories, then create them in tests with (for example):
*
* LineItemFactory();
*
* Or with attributes / overrides:
*
* LineItemFactory({
* "id": 123,
* "order": OrderFactory({"firstName": "Example Associated Record Override"}),
* "quantity": 4
* });
*/
(function(){
var setUpFactory = function(Type) {
var defaults = _.toArray(arguments).slice(1);
return function() {
var obj, objAttributes = [],
overrides = arguments,
collection = (defaults.length > overrides.length)? defaults : overrides;
// dynamically gather object defaults and overrides
for (var i = collection.length - 1; i >= 0; i--) {
var attributes = _.extend({}, defaults[i], overrides[i]);
objAttributes.unshift(attributes);
}
obj = Object.create(Type.prototype); // set up prototype chain
Type.apply(obj, objAttributes); // call constructor on the new object
return obj;
};
};
//// Factories ////
window.LineItemFactory = setUpFactory(LineItem, {
'id': randomId(),
'order': OrderFactory(),
'name': 'Some Product Name',
'price': '14.99',
'quantity': 1,
'path': '/products/some-product-name',
'availability': 'Available now (shipped in 3-5 days)',
'formatName': 'DVD',
'imageUrl': 'http://s3.amazonaws.com/myexample/assets/products/123/thumb.jpg?12345',
'variantOptions': 'Colour: Blue'
});
window.OrderFactory = setUpFactory(Order, {
'id': randomId(),
'number': 'E12345'
});
//// Misc Helpers ////
function randomId() {
return Math.floor(Math.random() * 999999) + 1;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment