-
-
Save trinonsense/9219151 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
* 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