ember-data-factory-guy 0.9.1 → 0.9.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -1 +1 @@
1
- var Sequence=function(fn){var index=1;this.next=function(){return fn.call(this,index++)};this.reset=function(){index=1}};var MissingSequenceError=function(message){this.toString=function(){return message}};if(FactoryGuy!==undefined){FactoryGuy.sequence=Sequence;FactoryGuy.missingSequenceError=MissingSequenceError}var ModelDefinition=function(model,config){var sequences={};var traits={};var defaultAttributes={};var namedModels={};var modelId=1;var sequenceName=null;this.model=model;this.matchesName=function(name){return model==name||namedModels[name]};this.nextId=function(){return modelId++};this.generate=function(name,sequenceFn){if(sequenceFn){if(!sequences[name]){sequences[name]=new Sequence(sequenceFn)}}var sequence=sequences[name];if(!sequence){throw new MissingSequenceError("Can not find that sequence named ["+sequenceName+"] in '"+model+"' definition")}return sequence.next()};this.build=function(name,opts,traitArgs){var traitsObj={};traitArgs.forEach(function(trait){$.extend(traitsObj,traits[trait])});var modelAttributes=namedModels[name]||{};var fixture=$.extend({},defaultAttributes,modelAttributes,traitsObj,opts);for(var attribute in fixture){if(Ember.typeOf(fixture[attribute])=="function"){fixture[attribute]=fixture[attribute].call(this,fixture)}else if(Ember.typeOf(fixture[attribute])=="object"){if(FactoryGuy.getStore()){if(FactoryGuy.isAttributeRelationship(this.model,attribute)){fixture[attribute]=FactoryGuy.build(attribute,fixture[attribute])}}else{fixture[attribute]=FactoryGuy.build(attribute,fixture[attribute])}}}if(!fixture.id){fixture.id=this.nextId()}return fixture};this.buildList=function(name,number,traits,opts){var arr=[];for(var i=0;i<number;i++){arr.push(this.build(name,opts,traits))}return arr};this.reset=function(){modelId=1;for(var name in sequences){sequences[name].reset()}};var parseDefault=function(object){if(!object){return}defaultAttributes=object};var parseTraits=function(object){if(!object){return}traits=object};var parseSequences=function(object){if(!object){return}for(sequenceName in object){var sequenceFn=object[sequenceName];if(Ember.typeOf(sequenceFn)!="function"){throw new Error("Problem with ["+sequenceName+"] sequence definition. Sequences must be functions")}object[sequenceName]=new Sequence(sequenceFn)}sequences=object};var parseConfig=function(config){parseSequences(config.sequences);delete config.sequences;parseTraits(config.traits);delete config.traits;parseDefault(config.default);delete config.default;namedModels=config};parseConfig(config)};if(FactoryGuy!==undefined){FactoryGuy.modelDefiniton=ModelDefinition}var FactoryGuy={modelDefinitions:{},define:function(model,config){if(this.modelDefinitions[model]){this.modelDefinitions[model].merge(config)}else{this.modelDefinitions[model]=new ModelDefinition(model,config)}},setStore:function(store){Ember.assert("FactoryGuy#setStore needs a valid store instance.You passed in ["+store+"]",store instanceof DS.Store);this.store=store},getStore:function(){return this.store},isAttributeRelationship:function(typeName,attribute){if(!this.store){console.log("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures");return true}var model=this.store.modelFor(typeName);return!!model.typeForRelationship(attribute)},make:function(){Ember.assert("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures",this.store);return this.store.makeFixture.apply(this.store,arguments)},generate:function(nameOrFunction){var sortaRandomName=Math.floor((1+Math.random())*65536).toString(16)+Date.now();return function(){if(Em.typeOf(nameOrFunction)=="function"){return this.generate(sortaRandomName,nameOrFunction)}else{return this.generate(nameOrFunction)}}},belongsTo:function(fixtureName,opts){return function(){return FactoryGuy.build(fixtureName,opts)}},association:function(fixtureName,opts){console.log("DEPRECATION Warning: use FactoryGuy.belongsTo instead");return this.belongsTo(fixtureName,opts)},hasMany:function(fixtureName,number,opts){return function(){return FactoryGuy.buildList(fixtureName,number,opts)}},lookupModelForFixtureName:function(name){var definition=this.lookupDefinitionForFixtureName(name);if(definition){return definition.model}},lookupDefinitionForFixtureName:function(name){for(var model in this.modelDefinitions){var definition=this.modelDefinitions[model];if(definition.matchesName(name)){return definition}}},build:function(){var args=Array.prototype.slice.call(arguments);var opts={};var name=args.shift();if(!name){throw new Error("Build needs a factory name to build")}if(Ember.typeOf(args[args.length-1])=="object"){opts=args.pop()}var traits=args;var definition=this.lookupDefinitionForFixtureName(name);if(!definition){throw new Error("Can't find that factory named ["+name+"]")}return definition.build(name,opts,traits)},buildList:function(){var args=Array.prototype.slice.call(arguments);var name=args.shift();var number=args.shift();if(!name||!number){throw new Error("buildList needs a name and a number ( at least ) to build with")}var opts={};if(Ember.typeOf(args[args.length-1])=="object"){opts=args.pop()}var traits=args;var definition=this.lookupDefinitionForFixtureName(name);if(!definition){throw new Error("Can't find that factory named ["+name+"]")}return definition.buildList(name,number,traits,opts)},resetModels:function(store){for(var model in this.modelDefinitions){var definition=this.modelDefinitions[model];definition.reset();try{var modelType=store.modelFor(definition.model);if(store.usingFixtureAdapter()){modelType.FIXTURES=[]}store.unloadAll(modelType)}catch(e){console.log("resetModels",e)}}},pushFixture:function(modelClass,fixture){var index;if(!modelClass.FIXTURES){modelClass.FIXTURES=[]}index=this.indexOfFixture(modelClass.FIXTURES,fixture);if(index>-1){modelClass.FIXTURES.splice(index,1)}modelClass.FIXTURES.push(fixture);return fixture},indexOfFixture:function(fixtures,fixture){var index=-1,id=fixture.id+"";Ember.A(fixtures).find(function(r,i){if(""+Ember.get(r,"id")===id){index=i;return true}else{return false}});return index},clear:function(opts){if(!opts){this.modelDefinitions={}}}};(function(){DS.Store.reopen({usingFixtureAdapter:function(){var adapter=this.adapterFor("application");return adapter instanceof DS.FixtureAdapter},makeFixture:function(){var store=this;var fixture=FactoryGuy.build.apply(FactoryGuy,arguments);var name=arguments[0];var modelName=FactoryGuy.lookupModelForFixtureName(name);var modelType=store.modelFor(modelName);if(this.usingFixtureAdapter()){this.setAssociationsForFixtureAdapter(modelType,modelName,fixture);return FactoryGuy.pushFixture(modelType,fixture)}else{return store.makeModel(modelType,fixture)}},makeModel:function(modelType,fixture){var store=this,modelName=store.modelFor(modelType).typeKey,model;Em.run(function(){store.findEmbeddedAssociationsForRESTAdapter(modelType,fixture);if(fixture.type){modelName=fixture.type.underscore();modelType=store.modelFor(modelName)}model=store.push(modelName,fixture);store.setAssociationsForRESTAdapter(modelType,modelName,model)});return model},makeList:function(){var arr=[];var number=arguments[1];for(var i=0;i<number;i++){arr.push(this.makeFixture.apply(this,arguments))}return arr},setAssociationsForFixtureAdapter:function(modelType,modelName,fixture){var self=this;var adapter=this.adapterFor("application");Ember.get(modelType,"relationshipsByName").forEach(function(relationship,name){if(relationship.kind=="hasMany"){var hasManyRelation=fixture[relationship.key];if(hasManyRelation){$.each(fixture[relationship.key],function(index,object){var id=object;if(Ember.typeOf(object)=="object"){id=object.id;hasManyRelation[index]=id}var hasManyfixtures=adapter.fixturesForType(relationship.type);var fixture=adapter.findFixtureById(hasManyfixtures,id);fixture[modelName]=fixture.id})}}if(relationship.kind=="belongsTo"){var belongsToRecord=fixture[relationship.key];if(belongsToRecord){if(typeof belongsToRecord=="object"){FactoryGuy.pushFixture(relationship.type,belongsToRecord);fixture[relationship.key]=belongsToRecord.id}var hasManyName=self.findHasManyRelationshipNameForFixtureAdapter(relationship.type,relationship.parentType);var belongsToFixtures=adapter.fixturesForType(relationship.type);var belongsTofixture=adapter.findFixtureById(belongsToFixtures,fixture[relationship.key]);if(!belongsTofixture[hasManyName]){belongsTofixture[hasManyName]=[]}belongsTofixture[hasManyName].push(fixture.id)}}})},findEmbeddedAssociationsForRESTAdapter:function(modelType,fixture){var store=this;Ember.get(modelType,"relationshipsByName").forEach(function(relationship,name){if(relationship.kind=="belongsTo"){var belongsToRecord=fixture[relationship.key];if(Ember.typeOf(belongsToRecord)=="object"){store.findEmbeddedAssociationsForRESTAdapter(relationship.type,belongsToRecord);belongsToRecord=store.push(relationship.type,belongsToRecord);fixture[relationship.key]=belongsToRecord}}if(relationship.kind=="hasMany"){var hasManyRecords=fixture[relationship.key];if(Ember.typeOf(hasManyRecords)=="array"){if(Ember.typeOf(hasManyRecords[0])=="object"){var records=Em.A();hasManyRecords.map(function(object){store.findEmbeddedAssociationsForRESTAdapter(relationship.type,object);var record=store.push(relationship.type,object);records.push(record);return record});fixture[relationship.key]=records}}}})},setAssociationsForRESTAdapter:function(modelType,modelName,model){var self=this;Ember.get(modelType,"relationshipsByName").forEach(function(relationship,name){if(relationship.kind=="hasMany"){var children=model.get(name)||[];children.forEach(function(child){var belongsToName=self.findRelationshipName("belongsTo",child.constructor,model);if(belongsToName){child.set(belongsToName,model)}})}})},findRelationshipName:function(kind,belongToModelType,childModel){var relationshipName;Ember.get(belongToModelType,"relationshipsByName").forEach(function(relationship,name){if(relationship.kind==kind&&childModel instanceof relationship.type){relationshipName=relationship.key}});return relationshipName},findHasManyRelationshipNameForFixtureAdapter:function(belongToModelType,childModelType){var relationshipName;Ember.get(belongToModelType,"relationshipsByName").forEach(function(relationship,name){if(relationship.kind=="hasMany"&&childModelType==relationship.type){relationshipName=relationship.key}});return relationshipName},pushPayload:function(type,payload){if(this.usingFixtureAdapter()){var model=this.modelFor(type);FactoryGuy.pushFixture(model,payload)}else{this._super(type,payload)}}})})();var FactoryGuyTestMixin=Em.Mixin.create({setup:function(app){this.set("container",app.__container__);FactoryGuy.setStore(this.getStore());return this},useFixtureAdapter:function(app){app.ApplicationAdapter=DS.FixtureAdapter;this.getStore().adapterFor("application").simulateRemoteResponse=false},usingActiveModelSerializer:function(type){var store=this.getStore();var modelType=store.modelFor(type);var serializer=store.serializerFor(modelType.typeKey);return serializer instanceof DS.ActiveModelSerializer},find:function(type,id){return this.getStore().find(type,id)},make:function(){var store=this.getStore();return store.makeFixture.apply(store,arguments)},getStore:function(){return this.get("container").lookup("store:main")},stubEndpointForHttpRequest:function(url,json,options){options=options||{};var request={url:url,dataType:"json",responseText:json,type:options.type||"GET",status:options.status||200};if(options.data){request.data=options.data}$.mockjax(request)},buildURL:function(typeName,id){var type=this.getStore().modelFor(typeName);return this.getStore().adapterFor(type).buildURL(type.typeKey,id)},handleFindMany:function(){var store=this.getStore();store.makeList.apply(store,arguments);var name=arguments[0];var modelName=FactoryGuy.lookupModelForFixtureName(name);var responseJson={};responseJson[modelName]=[];var url=this.buildURL(modelName);this.stubEndpointForHttpRequest(url,responseJson,{type:"GET"})},handleCreate:function(modelName,options){var opts=options===undefined?{}:options;var succeed=opts.succeed===undefined?true:opts.succeed;var match=opts.match||{};var returnArgs=opts.returns||{};var url=this.buildURL(modelName);var definition=FactoryGuy.modelDefinitions[modelName];var httpOptions={type:"POST"};if(opts.match){var expectedRequest={};var record=this.getStore().createRecord(modelName,match);expectedRequest[modelName]=record.serialize();httpOptions.data=JSON.stringify(expectedRequest)}var modelType=this.getStore().modelFor(modelName);var responseJson={};if(succeed){responseJson[modelName]=$.extend({id:definition.nextId()},match,returnArgs);Ember.get(modelType,"relationshipsByName").forEach(function(relationship){if(relationship.kind=="belongsTo"){delete responseJson[modelName][relationship.key]}})}else{httpOptions.status=500}this.stubEndpointForHttpRequest(url,responseJson,httpOptions)},handleUpdate:function(){var args=Array.prototype.slice.call(arguments);Ember.assert("To handleUpdate pass in a model instance or a type and an id",args.length>0);var succeed=true;if(typeof args[args.length-1]=="boolean"){args.pop();succeed=false}Ember.assert("To handleUpdate pass in a model instance or a type and an id",args.length>0);var type,id;if(args[0]instanceof DS.Model){var model=args[0];type=model.constructor.typeKey;id=model.id}else if(typeof args[0]=="string"&&typeof parseInt(args[1])=="number"){type=args[0];id=args[1]}Ember.assert("To handleUpdate pass in a model instance or a type and an id",type&&id);this.stubEndpointForHttpRequest(this.buildURL(type,id),{},{type:"PUT",status:succeed?200:500})},handleDelete:function(type,id,succeed){succeed=succeed===undefined?true:succeed;this.stubEndpointForHttpRequest(this.buildURL(type,id),{},{type:"DELETE",status:succeed?200:500})},teardown:function(){FactoryGuy.resetModels(this.getStore());$.mockjax.clear()}});if(FactoryGuy!==undefined){FactoryGuy.testMixin=FactoryGuyTestMixin}
1
+ var Sequence=function(fn){var index=1;this.next=function(){return fn.call(this,index++)};this.reset=function(){index=1}};var MissingSequenceError=function(message){this.toString=function(){return message}};if(FactoryGuy!==undefined){FactoryGuy.sequence=Sequence;FactoryGuy.missingSequenceError=MissingSequenceError}var ModelDefinition=function(model,config){var sequences={};var traits={};var defaultAttributes={};var namedModels={};var modelId=1;var sequenceName=null;this.model=model;this.matchesName=function(name){return model==name||namedModels[name]};this.nextId=function(){return modelId++};this.generate=function(name,sequenceFn){if(sequenceFn){if(!sequences[name]){sequences[name]=new Sequence(sequenceFn)}}var sequence=sequences[name];if(!sequence){throw new MissingSequenceError("Can not find that sequence named ["+sequenceName+"] in '"+model+"' definition")}return sequence.next()};this.build=function(name,opts,traitArgs){var traitsObj={};traitArgs.forEach(function(trait){$.extend(traitsObj,traits[trait])});var modelAttributes=namedModels[name]||{};var fixture=$.extend({},defaultAttributes,modelAttributes,traitsObj,opts);for(var attribute in fixture){if(Ember.typeOf(fixture[attribute])=="function"){fixture[attribute]=fixture[attribute].call(this,fixture)}else if(Ember.typeOf(fixture[attribute])=="object"){if(FactoryGuy.getStore()){if(FactoryGuy.isAttributeRelationship(this.model,attribute)){fixture[attribute]=FactoryGuy.build(attribute,fixture[attribute])}}else{fixture[attribute]=FactoryGuy.build(attribute,fixture[attribute])}}}if(!fixture.id){fixture.id=this.nextId()}return fixture};this.buildList=function(name,number,traits,opts){var arr=[];for(var i=0;i<number;i++){arr.push(this.build(name,opts,traits))}return arr};this.reset=function(){modelId=1;for(var name in sequences){sequences[name].reset()}};var parseDefault=function(object){if(!object){return}defaultAttributes=object};var parseTraits=function(object){if(!object){return}traits=object};var parseSequences=function(object){if(!object){return}for(sequenceName in object){var sequenceFn=object[sequenceName];if(Ember.typeOf(sequenceFn)!="function"){throw new Error("Problem with ["+sequenceName+"] sequence definition. Sequences must be functions")}object[sequenceName]=new Sequence(sequenceFn)}sequences=object};var parseConfig=function(config){parseSequences(config.sequences);delete config.sequences;parseTraits(config.traits);delete config.traits;parseDefault(config.default);delete config.default;namedModels=config};parseConfig(config)};if(FactoryGuy!==undefined){FactoryGuy.modelDefiniton=ModelDefinition}var FactoryGuy={modelDefinitions:{},define:function(model,config){if(this.modelDefinitions[model]){this.modelDefinitions[model].merge(config)}else{this.modelDefinitions[model]=new ModelDefinition(model,config)}},setStore:function(store){Ember.assert("FactoryGuy#setStore needs a valid store instance.You passed in ["+store+"]",store instanceof DS.Store);this.store=store},getStore:function(){return this.store},isAttributeRelationship:function(typeName,attribute){if(!this.store){Ember.debug("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures");return true}var model=this.store.modelFor(typeName);return!!model.typeForRelationship(attribute)},generate:function(nameOrFunction){var sortaRandomName=Math.floor((1+Math.random())*65536).toString(16)+Date.now();return function(){if(Em.typeOf(nameOrFunction)=="function"){return this.generate(sortaRandomName,nameOrFunction)}else{return this.generate(nameOrFunction)}}},belongsTo:function(fixtureName,opts){return function(){return FactoryGuy.build(fixtureName,opts)}},association:function(fixtureName,opts){Ember.deprecate("DEPRECATION Warning: use FactoryGuy.belongsTo instead");return this.belongsTo(fixtureName,opts)},hasMany:function(fixtureName,number,opts){return function(){return FactoryGuy.buildList(fixtureName,number,opts)}},lookupModelForFixtureName:function(name){var definition=this.lookupDefinitionForFixtureName(name);if(definition){return definition.model}},lookupDefinitionForFixtureName:function(name){for(var model in this.modelDefinitions){var definition=this.modelDefinitions[model];if(definition.matchesName(name)){return definition}}},build:function(){var args=Array.prototype.slice.call(arguments);var opts={};var name=args.shift();if(!name){throw new Error("Build needs a factory name to build")}if(Ember.typeOf(args[args.length-1])=="object"){opts=args.pop()}var traits=args;var definition=this.lookupDefinitionForFixtureName(name);if(!definition){throw new Error("Can't find that factory named ["+name+"]")}return definition.build(name,opts,traits)},buildList:function(){var args=Array.prototype.slice.call(arguments);var name=args.shift();var number=args.shift();if(!name||!number){throw new Error("buildList needs a name and a number ( at least ) to build with")}var opts={};if(Ember.typeOf(args[args.length-1])=="object"){opts=args.pop()}var traits=args;var definition=this.lookupDefinitionForFixtureName(name);if(!definition){throw new Error("Can't find that factory named ["+name+"]")}return definition.buildList(name,number,traits,opts)},make:function(){var store=this.store;Ember.assert("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures",store);var fixture=this.build.apply(this,arguments);var name=arguments[0];var modelName=this.lookupModelForFixtureName(name);var modelType=store.modelFor(modelName);if(store.usingFixtureAdapter()){store.setAssociationsForFixtureAdapter(modelType,modelName,fixture);return this.pushFixture(modelType,fixture)}else{return store.makeModel(modelType,fixture)}},makeList:function(){Ember.assert("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures",this.store);var arr=[];var args=Array.prototype.slice.call(arguments);Ember.assert("makeList needs at least 2 arguments, a name and a number",args.length>=2);var number=args.splice(1,1)[0];Ember.assert("Second argument to makeList should be a number (of fixtures to make.)",typeof number=="number");for(var i=0;i<number;i++){arr.push(this.make.apply(this,args))}return arr},resetModels:function(store){for(var model in this.modelDefinitions){var definition=this.modelDefinitions[model];definition.reset();try{var modelType=store.modelFor(definition.model);if(store.usingFixtureAdapter()){modelType.FIXTURES=[]}store.unloadAll(modelType)}catch(e){console.log("resetModels",e)}}},pushFixture:function(modelClass,fixture){var index;if(!modelClass.FIXTURES){modelClass.FIXTURES=[]}index=this.indexOfFixture(modelClass.FIXTURES,fixture);if(index>-1){modelClass.FIXTURES.splice(index,1)}modelClass.FIXTURES.push(fixture);return fixture},indexOfFixture:function(fixtures,fixture){var index=-1,id=fixture.id+"";Ember.A(fixtures).find(function(r,i){if(""+Ember.get(r,"id")===id){index=i;return true}else{return false}});return index},clear:function(opts){if(!opts){this.modelDefinitions={}}}};(function(){DS.Store.reopen({usingFixtureAdapter:function(){var adapter=this.adapterFor("application");return adapter instanceof DS.FixtureAdapter},makeFixture:function(){Ember.deprecate("DEPRECATION Warning: use FactoryGuy.make instead");FactoryGuy.make.call(FactoryGuy,arguments)},makeList:function(){Ember.deprecate("DEPRECATION Warning: use FactoryGuy.makeList instead");FactoryGuy.makeList.call(FactoryGuy,arguments)},makeModel:function(modelType,fixture){var store=this,modelName=store.modelFor(modelType).typeKey,model;Em.run(function(){store.findEmbeddedAssociationsForRESTAdapter(modelType,fixture);if(fixture.type){modelName=fixture.type.underscore();modelType=store.modelFor(modelName)}model=store.push(modelName,fixture);store.setAssociationsForRESTAdapter(modelType,modelName,model)});return model},setAssociationsForFixtureAdapter:function(modelType,modelName,fixture){var self=this;var adapter=this.adapterFor("application");Ember.get(modelType,"relationshipsByName").forEach(function(relationship,name){if(relationship.kind=="hasMany"){var hasManyRelation=fixture[relationship.key];if(hasManyRelation){$.each(fixture[relationship.key],function(index,object){var id=object;if(Ember.typeOf(object)=="object"){id=object.id;hasManyRelation[index]=id}var hasManyfixtures=adapter.fixturesForType(relationship.type);var fixture=adapter.findFixtureById(hasManyfixtures,id);fixture[modelName]=fixture.id})}}if(relationship.kind=="belongsTo"){var belongsToRecord=fixture[relationship.key];if(belongsToRecord){if(typeof belongsToRecord=="object"){FactoryGuy.pushFixture(relationship.type,belongsToRecord);fixture[relationship.key]=belongsToRecord.id}var hasManyName=self.findHasManyRelationshipNameForFixtureAdapter(relationship.type,relationship.parentType);var belongsToFixtures=adapter.fixturesForType(relationship.type);var belongsTofixture=adapter.findFixtureById(belongsToFixtures,fixture[relationship.key]);if(!belongsTofixture[hasManyName]){belongsTofixture[hasManyName]=[]}belongsTofixture[hasManyName].push(fixture.id)}}})},findEmbeddedAssociationsForRESTAdapter:function(modelType,fixture){var store=this;Ember.get(modelType,"relationshipsByName").forEach(function(relationship,name){if(relationship.kind=="belongsTo"){var belongsToRecord=fixture[relationship.key];if(Ember.typeOf(belongsToRecord)=="object"){store.findEmbeddedAssociationsForRESTAdapter(relationship.type,belongsToRecord);belongsToRecord=store.push(relationship.type,belongsToRecord);fixture[relationship.key]=belongsToRecord}}if(relationship.kind=="hasMany"){var hasManyRecords=fixture[relationship.key];if(Ember.typeOf(hasManyRecords)=="array"){if(Ember.typeOf(hasManyRecords[0])=="object"){var records=Em.A();hasManyRecords.map(function(object){store.findEmbeddedAssociationsForRESTAdapter(relationship.type,object);var record=store.push(relationship.type,object);records.push(record);return record});fixture[relationship.key]=records}}}})},setAssociationsForRESTAdapter:function(modelType,modelName,model){var self=this;Ember.get(modelType,"relationshipsByName").forEach(function(relationship,name){if(relationship.kind=="hasMany"){var children=model.get(name)||[];children.forEach(function(child){var belongsToName=self.findRelationshipName("belongsTo",child.constructor,model);if(belongsToName){child.set(belongsToName,model)}})}})},findRelationshipName:function(kind,belongToModelType,childModel){var relationshipName;Ember.get(belongToModelType,"relationshipsByName").forEach(function(relationship,name){if(relationship.kind==kind&&childModel instanceof relationship.type){relationshipName=relationship.key}});return relationshipName},findHasManyRelationshipNameForFixtureAdapter:function(belongToModelType,childModelType){var relationshipName;Ember.get(belongToModelType,"relationshipsByName").forEach(function(relationship,name){if(relationship.kind=="hasMany"&&childModelType==relationship.type){relationshipName=relationship.key}});return relationshipName},pushPayload:function(type,payload){if(this.usingFixtureAdapter()){var model=this.modelFor(type);FactoryGuy.pushFixture(model,payload)}else{this._super(type,payload)}}})})();var FactoryGuyTestMixin=Em.Mixin.create({setup:function(app){this.set("container",app.__container__);FactoryGuy.setStore(this.getStore());return this},useFixtureAdapter:function(app){app.ApplicationAdapter=DS.FixtureAdapter;this.getStore().adapterFor("application").simulateRemoteResponse=false},usingActiveModelSerializer:function(type){var store=this.getStore();var modelType=store.modelFor(type);var serializer=store.serializerFor(modelType.typeKey);return serializer instanceof DS.ActiveModelSerializer},find:function(type,id){return this.getStore().find(type,id)},make:function(){return FactoryGuy.make.apply(FactoryGuy,arguments)},getStore:function(){return this.get("container").lookup("store:main")},stubEndpointForHttpRequest:function(url,json,options){options=options||{};var request={url:url,dataType:"json",responseText:json,type:options.type||"GET",status:options.status||200};if(options.urlParams){request.urlParams=options.urlParams}if(options.data){request.data=options.data}$.mockjax(request)},buildURL:function(typeName,id){var type=this.getStore().modelFor(typeName);return this.getStore().adapterFor(type).buildURL(type.typeKey,id)},handleFindMany:function(){FactoryGuy.makeList.apply(FactoryGuy,arguments);var name=arguments[0];var modelName=FactoryGuy.lookupModelForFixtureName(name);var responseJson={};responseJson[modelName]=[];var url=this.buildURL(modelName);this.stubEndpointForHttpRequest(url,responseJson)},handleFindQuery:function(modelName,searchParams,json){var responseJson={};responseJson[modelName.pluralize()]=json;var url=this.buildURL(modelName);this.stubEndpointForHttpRequest(url,responseJson,{urlParams:searchParams})},handleCreate:function(modelName,options){var opts=options===undefined?{}:options;var succeed=opts.succeed===undefined?true:opts.succeed;var match=opts.match||{};var returnArgs=opts.returns||{};var url=this.buildURL(modelName);var definition=FactoryGuy.modelDefinitions[modelName];var httpOptions={type:"POST"};if(opts.match){var expectedRequest={};var record=this.getStore().createRecord(modelName,match);expectedRequest[modelName]=record.serialize();httpOptions.data=JSON.stringify(expectedRequest)}var modelType=this.getStore().modelFor(modelName);var responseJson={};if(succeed){responseJson[modelName]=$.extend({id:definition.nextId()},match,returnArgs);Ember.get(modelType,"relationshipsByName").forEach(function(relationship){if(relationship.kind=="belongsTo"){delete responseJson[modelName][relationship.key]}})}else{httpOptions.status=500}this.stubEndpointForHttpRequest(url,responseJson,httpOptions)},handleUpdate:function(){var args=Array.prototype.slice.call(arguments);Ember.assert("To handleUpdate pass in a model instance or a type and an id",args.length>0);var succeed=true;if(typeof args[args.length-1]=="boolean"){args.pop();succeed=false}Ember.assert("To handleUpdate pass in a model instance or a type and an id",args.length>0);var type,id;if(args[0]instanceof DS.Model){var model=args[0];type=model.constructor.typeKey;id=model.id}else if(typeof args[0]=="string"&&typeof parseInt(args[1])=="number"){type=args[0];id=args[1]}Ember.assert("To handleUpdate pass in a model instance or a type and an id",type&&id);this.stubEndpointForHttpRequest(this.buildURL(type,id),{},{type:"PUT",status:succeed?200:500})},handleDelete:function(type,id,succeed){succeed=succeed===undefined?true:succeed;this.stubEndpointForHttpRequest(this.buildURL(type,id),{},{type:"DELETE",status:succeed?200:500})},teardown:function(){FactoryGuy.resetModels(this.getStore());$.mockjax.clear()}});if(FactoryGuy!==undefined){FactoryGuy.testMixin=FactoryGuyTestMixin}
@@ -1,7 +1,7 @@
1
1
  # -*- encoding: utf-8 -*-
2
2
  Gem::Specification.new do |s|
3
3
  s.name = "ember-data-factory-guy"
4
- s.version = "0.9.1"
4
+ s.version = "0.9.2"
5
5
  s.platform = Gem::Platform::RUBY
6
6
  s.authors = ["Daniel Sudol", "Alex Opak"]
7
7
  s.email = ["dansudol@yahoo.com", "opak.alexandr@gmail.com"]
data/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ember-data-factory-guy",
3
- "version": "0.9.1",
3
+ "version": "0.9.2",
4
4
  "authors": [
5
5
  "Daniel Sudol <dansudol@yahoo.com>",
6
6
  "Opak Alex <opak.alexandr@gmail.com>"
data/src/factory_guy.js CHANGED
@@ -71,18 +71,6 @@ var FactoryGuy = {
71
71
  var model = this.store.modelFor(typeName);
72
72
  return !!model.typeForRelationship(attribute);
73
73
  },
74
- /**
75
- Make new fixture and save to store. Proxy to store#makeFixture method
76
-
77
- @param {String} name fixture name
78
- @param {String} trait optional trait names ( one or more )
79
- @param {Object} opts optional fixture options that will override default fixture values
80
- @returns {Object|DS.Model} json or record depending on the adapter type
81
- */
82
- make: function() {
83
- Ember.assert("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures", this.store);
84
- return this.store.makeFixture.apply(this.store,arguments);
85
- },
86
74
  /**
87
75
  Used in model definitions to declare use of a sequence. For example:
88
76
 
@@ -277,7 +265,53 @@ var FactoryGuy = {
277
265
  }
278
266
  return definition.buildList(name, number, traits, opts);
279
267
  },
268
+ /**
269
+ Make new fixture and save to store.
280
270
 
271
+ @param {String} name fixture name
272
+ @param {String} trait optional trait names ( one or more )
273
+ @param {Object} options optional fixture options that will override default fixture values
274
+ @returns {Object|DS.Model} json or record depending on the adapter type
275
+ */
276
+ make: function() {
277
+ var store = this.store;
278
+ Ember.assert("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures", store);
279
+
280
+ var fixture = this.build.apply(this, arguments);
281
+ var name = arguments[0];
282
+ var modelName = this.lookupModelForFixtureName(name);
283
+ var modelType = store.modelFor(modelName);
284
+
285
+ if (store.usingFixtureAdapter()) {
286
+ store.setAssociationsForFixtureAdapter(modelType, modelName, fixture);
287
+ return this.pushFixture(modelType, fixture);
288
+ } else {
289
+ return store.makeModel(modelType, fixture);
290
+ }
291
+ },
292
+ /**
293
+ Make a list of Fixtures
294
+
295
+ @param {String} name name of fixture
296
+ @param {Number} number number to create
297
+ @param {String} trait optional trait names ( one or more )
298
+ @param {Object} options optional fixture options that will override default fixture values
299
+ @returns {Array} list of json fixtures or records depending on the adapter type
300
+ */
301
+ makeList: function() {
302
+ Ember.assert("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures", this.store);
303
+
304
+ var arr = [];
305
+ var args = Array.prototype.slice.call(arguments);
306
+ Ember.assert("makeList needs at least 2 arguments, a name and a number",args.length >= 2);
307
+ var number = args.splice(1,1)[0];
308
+ Ember.assert("Second argument to makeList should be a number (of fixtures to make.)",typeof number == 'number');
309
+
310
+ for (var i = 0; i < number; i++) {
311
+ arr.push(this.make.apply(this, args));
312
+ }
313
+ return arr;
314
+ },
281
315
  /**
282
316
  Clear model instances from FIXTURES array, and from store cache.
283
317
  Reset the id sequence for the models back to zero.
@@ -30,11 +30,10 @@ var FactoryGuyTestMixin = Em.Mixin.create({
30
30
  return this.getStore().find(type, id);
31
31
  },
32
32
  /**
33
- Make new fixture and save to store. Proxy to store#makeFixture method
33
+ Make new fixture and save to store. Proxy to FactoryGuy#make method
34
34
  */
35
35
  make: function () {
36
- var store = this.getStore();
37
- return store.makeFixture.apply(store, arguments);
36
+ return FactoryGuy.make.apply(FactoryGuy, arguments);
38
37
  },
39
38
  getStore: function () {
40
39
  return this.get('container').lookup('store:main');
@@ -55,6 +54,9 @@ var FactoryGuyTestMixin = Em.Mixin.create({
55
54
  type: options.type || 'GET',
56
55
  status: options.status || 200
57
56
  };
57
+ if (options.urlParams) {
58
+ request.urlParams = options.urlParams;
59
+ }
58
60
  if (options.data) {
59
61
  request.data = options.data;
60
62
  }
@@ -81,9 +83,8 @@ var FactoryGuyTestMixin = Em.Mixin.create({
81
83
  @param {Object} opts optional fixture options
82
84
  */
83
85
  handleFindMany: function () {
84
- var store = this.getStore();
85
86
  // make the records and load them in the store
86
- store.makeList.apply(store, arguments);
87
+ FactoryGuy.makeList.apply(FactoryGuy, arguments);
87
88
  var name = arguments[0];
88
89
  var modelName = FactoryGuy.lookupModelForFixtureName(name);
89
90
  var responseJson = {};
@@ -91,7 +92,35 @@ var FactoryGuyTestMixin = Em.Mixin.create({
91
92
  var url = this.buildURL(modelName);
92
93
  // mock the ajax call, but return nothing, since the records will be
93
94
  // retrieved from the store where they were just loaded above
94
- this.stubEndpointForHttpRequest(url, responseJson, { type: 'GET' });
95
+ this.stubEndpointForHttpRequest(url, responseJson);
96
+ },
97
+ /**
98
+ Handling ajax GET for finding all records for a type of model with query parameters.
99
+
100
+ ```js
101
+ // First build json for the instances you want 'returned' in your query.
102
+ var usersJson = FactoryGuy.buildList('user', 2);
103
+
104
+ // Pass in the parameters you will search on ( in this case 'name' and 'age' ) as an array,
105
+ // in the second argument.
106
+ testHelper.handleFindQuery('user', ['name', 'age'], usersJson);
107
+
108
+ store.findQuery('user', {name:'Bob', age: 10}}).then(function(userInstances){
109
+ /// userInstances were created from the usersJson that you passed in
110
+ })
111
+ ```
112
+
113
+ The model instances will be created from the json you have passed in.
114
+
115
+ @param {String} modelName name of the mode like 'user' for User model type
116
+ @param {String} searchParams the parameters that will be queried
117
+ @param {Object} json fixture json used to build the resulting modelType instances
118
+ */
119
+ handleFindQuery: function (modelName, searchParams, json) {
120
+ var responseJson = {};
121
+ responseJson[modelName.pluralize()] = json;
122
+ var url = this.buildURL(modelName);
123
+ this.stubEndpointForHttpRequest(url, responseJson, {urlParams: searchParams});
95
124
  },
96
125
  /**
97
126
  Handling ajax POST ( create record ) for a model. You can mock
data/src/store.js CHANGED
@@ -8,30 +8,30 @@
8
8
  return adapter instanceof DS.FixtureAdapter;
9
9
  },
10
10
  /**
11
- Make new fixture and save to store. If the store is using FixtureAdapter,
12
- will push to FIXTURE array, otherwise will use push method on adapter to load
13
- the record into the store
14
-
15
- @param {String} name fixture name
16
- @param {String} trait optional trait names ( one or more )
17
- @param {Object} opts optional fixture options that will override default fixture values
18
- @returns {Object|DS.Model} json or record depending on the adapter type
11
+ Deprecated in favor of FactoryGuy.make
19
12
  */
20
13
  makeFixture: function () {
21
- var store = this;
22
- var fixture = FactoryGuy.build.apply(FactoryGuy, arguments);
23
- var name = arguments[0];
24
- var modelName = FactoryGuy.lookupModelForFixtureName(name);
25
- var modelType = store.modelFor(modelName);
26
- if (this.usingFixtureAdapter()) {
27
- this.setAssociationsForFixtureAdapter(modelType, modelName, fixture);
28
- return FactoryGuy.pushFixture(modelType, fixture);
29
- } else {
30
- return store.makeModel(modelType, fixture);
31
- }
14
+ Ember.deprecate('DEPRECATION Warning: use FactoryGuy.make instead');
15
+ FactoryGuy.make.call(FactoryGuy, arguments)
16
+ },
17
+ /**
18
+ Deprecated in favor of FactoryGuy.makeList
19
+ */
20
+ makeList: function () {
21
+ Ember.deprecate('DEPRECATION Warning: use FactoryGuy.makeList instead');
22
+ FactoryGuy.makeList.call(FactoryGuy, arguments)
32
23
  },
24
+ /**
25
+ * Most of the work of making the model from the json fixture is going on here.
26
+ * @param modelType
27
+ * @param fixture
28
+ * @returns {*}
29
+ */
33
30
  makeModel: function (modelType, fixture) {
34
- var store = this, modelName = store.modelFor(modelType).typeKey, model;
31
+ var store = this,
32
+ modelName = store.modelFor(modelType).typeKey,
33
+ model;
34
+
35
35
  Em.run(function () {
36
36
  store.findEmbeddedAssociationsForRESTAdapter(modelType, fixture);
37
37
  if (fixture.type) {
@@ -45,22 +45,6 @@
45
45
  });
46
46
  return model;
47
47
  },
48
- /**
49
- Make a list of Fixtures
50
-
51
- @param {String} name name of fixture
52
- @param {Number} number number to create
53
- @param {Object} options fixture options
54
- @returns {Array} list of json fixtures or records depending on the adapter type
55
- */
56
- makeList: function () {
57
- var arr = [];
58
- var number = arguments[1];
59
- for (var i = 0; i < number; i++) {
60
- arr.push(this.makeFixture.apply(this, arguments));
61
- }
62
- return arr;
63
- },
64
48
  /**
65
49
  Set the hasMany and belongsTo associations for FixtureAdapter.
66
50
 
@@ -5,7 +5,7 @@ module('FactoryGuy with ActiveModelAdapter', {
5
5
  setup: function() {
6
6
  testHelper = TestHelper.setup(DS.ActiveModelAdapter);
7
7
  store = testHelper.getStore();
8
- make = function() {return testHelper.make.apply(testHelper,arguments)}
8
+ make = function() {return FactoryGuy.make.apply(FactoryGuy,arguments)}
9
9
  },
10
10
  teardown: function() {
11
11
  testHelper.teardown();
@@ -35,11 +35,11 @@ test("#resetModels clears the store of models, and resets the model definition",
35
35
  });
36
36
 
37
37
 
38
- module('DS.Store#makeFixture with ActiveModelAdapter', {
38
+ module('#make with ActiveModelAdapter', {
39
39
  setup: function() {
40
40
  testHelper = TestHelper.setup(DS.ActiveModelAdapter);
41
41
  store = testHelper.getStore();
42
- make = function() {return testHelper.make.apply(testHelper,arguments)}
42
+ make = function() {return FactoryGuy.make.apply(FactoryGuy,arguments)}
43
43
  },
44
44
  teardown: function() {
45
45
  Em.run(function() { testHelper.teardown(); });
@@ -287,7 +287,7 @@ test("with (nested json fixture) belongsTo has a hasMany association which has a
287
287
  });
288
288
 
289
289
 
290
- module('DS.Store#makeList with ActiveModelAdapter', {
290
+ module('#makeList with ActiveModelAdapter', {
291
291
  setup: function() {
292
292
  testHelper = TestHelper.setup(DS.ActiveModelAdapter);
293
293
  store = testHelper.getStore();
@@ -299,7 +299,7 @@ module('DS.Store#makeList with ActiveModelAdapter', {
299
299
 
300
300
 
301
301
  test("creates list of DS.Model instances", function() {
302
- var users = store.makeList('user', 2);
302
+ var users = FactoryGuy.makeList('user', 2);
303
303
  equal(users.length, 2);
304
304
  ok(users[0] instanceof DS.Model == true);
305
305
 
@@ -308,3 +308,15 @@ test("creates list of DS.Model instances", function() {
308
308
  ok(storeUsers[1] == users[1]);
309
309
  });
310
310
 
311
+ test("handles trait arguments", function() {
312
+ var users = FactoryGuy.makeList('user', 2, 'with_hats');
313
+ equal(users.length, 2);
314
+ equal(users[0].get('hats.length') == 2, true);
315
+ });
316
+
317
+ test("handles traits and optional fixture arguments", function() {
318
+ var users = FactoryGuy.makeList('user', 2, 'with_hats', {name: 'Bob'});
319
+ equal(users[0].get('name'), 'Bob');
320
+ equal(users[0].get('hats.length') == 2, true);
321
+ });
322
+
@@ -242,7 +242,6 @@ module('FactoryGuy with DS.FixtureAdapter', {
242
242
 
243
243
 
244
244
  asyncTest("#make loads the fixture in the store and returns an object", function() {
245
- FactoryGuy.setStore(store);
246
245
  var user = FactoryGuy.make('user');
247
246
  ok(user instanceof Object )
248
247
  store.find('user', user.id).then(function(u){
@@ -54,6 +54,20 @@ asyncTest("#handleCreate the basic", function() {
54
54
  });
55
55
 
56
56
 
57
+ /////// handleFindQuery //////////
58
+
59
+ asyncTest("#handleFindQuery", function() {
60
+ var users = FactoryGuy.buildList('user', 2);
61
+ testHelper.handleFindQuery('user', ['name'], users);
62
+
63
+ store.findQuery('user', {name: 'Bob'}).then(function (users) {
64
+ equal(users.get('length'), 2)
65
+ equal(users.get('firstObject.name'), 'User1')
66
+ equal(users.get('lastObject.name'), 'User2')
67
+ start();
68
+ })
69
+ });
70
+
57
71
 
58
72
  /////// handleFindMany //////////
59
73
 
@@ -376,3 +390,5 @@ asyncTest("#handleDelete failure case", function() {
376
390
  }
377
391
  );
378
392
  });
393
+
394
+
@@ -4,7 +4,7 @@ module('FactoryGuy with DS.RESTAdapter', {
4
4
  setup: function() {
5
5
  testHelper = TestHelper.setup(DS.RESTAdapter);
6
6
  store = testHelper.getStore();
7
- make = function() {return testHelper.make.apply(testHelper,arguments)}
7
+ make = function() {return FactoryGuy.make.apply(FactoryGuy,arguments)}
8
8
  },
9
9
  teardown: function() {
10
10
  Em.run(function() { testHelper.teardown(); });
@@ -34,11 +34,11 @@ test("#resetModels clears the store of models, and resets the model definition",
34
34
  });
35
35
 
36
36
 
37
- module('DS.Store#makeFixture with RestAdapter', {
37
+ module('#make with RestAdapter', {
38
38
  setup: function() {
39
39
  testHelper = TestHelper.setup(DS.RESTAdapter);
40
40
  store = testHelper.getStore();
41
- make = function() {return testHelper.make.apply(testHelper,arguments)}
41
+ make = function() {return FactoryGuy.make.apply(FactoryGuy,arguments)}
42
42
  },
43
43
  teardown: function() {
44
44
  Em.run(function() { testHelper.teardown(); });
@@ -279,7 +279,7 @@ test("with (nested json fixture) belongsTo has a hasMany association which has a
279
279
  });
280
280
 
281
281
 
282
- module('DS.Store#makeList with DS.RESTAdapter', {
282
+ module('#makeList with DS.RESTAdapter', {
283
283
  setup: function() {
284
284
  testHelper = TestHelper.setup(DS.RESTAdapter);
285
285
  store = testHelper.getStore();
@@ -291,16 +291,24 @@ module('DS.Store#makeList with DS.RESTAdapter', {
291
291
 
292
292
 
293
293
  test("creates list of DS.Model instances", function() {
294
- var users = store.makeList('user', 2);
295
- ok(users.length == 2);
294
+ var users = FactoryGuy.makeList('user', 2);
295
+ equal(users.length, 2);
296
296
  ok(users[0] instanceof DS.Model == true);
297
- });
298
-
299
-
300
- test("creates records in the store", function() {
301
- var users = store.makeList('user', 2);
302
297
 
303
298
  var storeUsers = store.all('user').get('content');
304
299
  ok(storeUsers[0] == users[0]);
305
300
  ok(storeUsers[1] == users[1]);
306
- });
301
+ });
302
+
303
+ test("handles accept traits", function() {
304
+ var users = FactoryGuy.makeList('user', 2, 'with_hats');
305
+ equal(users.length, 2);
306
+ equal(users[0].get('hats.length') == 2, true);
307
+ });
308
+
309
+ test("handles accept traits and optional fixture arguments", function() {
310
+ var users = FactoryGuy.makeList('user', 2, 'with_hats', {name: 'Bob'});
311
+ equal(users[0].get('name'), 'Bob');
312
+ equal(users[0].get('hats.length') == 2, true);
313
+ });
314
+
@@ -242,25 +242,13 @@ var FactoryGuy = {
242
242
  */
243
243
  isAttributeRelationship: function(typeName, attribute) {
244
244
  if (!this.store) {
245
- console.log("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures")
245
+ Ember.debug("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures")
246
246
  // The legacy value was true.
247
247
  return true;
248
248
  }
249
249
  var model = this.store.modelFor(typeName);
250
250
  return !!model.typeForRelationship(attribute);
251
251
  },
252
- /**
253
- Make new fixture and save to store. Proxy to store#makeFixture method
254
-
255
- @param {String} name fixture name
256
- @param {String} trait optional trait names ( one or more )
257
- @param {Object} opts optional fixture options that will override default fixture values
258
- @returns {Object|DS.Model} json or record depending on the adapter type
259
- */
260
- make: function() {
261
- Ember.assert("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures", this.store);
262
- return this.store.makeFixture.apply(this.store,arguments);
263
- },
264
252
  /**
265
253
  Used in model definitions to declare use of a sequence. For example:
266
254
 
@@ -328,7 +316,7 @@ var FactoryGuy = {
328
316
  };
329
317
  },
330
318
  association: function (fixtureName, opts) {
331
- console.log('DEPRECATION Warning: use FactoryGuy.belongsTo instead');
319
+ Ember.deprecate('DEPRECATION Warning: use FactoryGuy.belongsTo instead');
332
320
  return this.belongsTo(fixtureName, opts);
333
321
  },
334
322
  /**
@@ -455,7 +443,53 @@ var FactoryGuy = {
455
443
  }
456
444
  return definition.buildList(name, number, traits, opts);
457
445
  },
446
+ /**
447
+ Make new fixture and save to store.
448
+
449
+ @param {String} name fixture name
450
+ @param {String} trait optional trait names ( one or more )
451
+ @param {Object} options optional fixture options that will override default fixture values
452
+ @returns {Object|DS.Model} json or record depending on the adapter type
453
+ */
454
+ make: function() {
455
+ var store = this.store;
456
+ Ember.assert("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures", store);
457
+
458
+ var fixture = this.build.apply(this, arguments);
459
+ var name = arguments[0];
460
+ var modelName = this.lookupModelForFixtureName(name);
461
+ var modelType = store.modelFor(modelName);
462
+
463
+ if (store.usingFixtureAdapter()) {
464
+ store.setAssociationsForFixtureAdapter(modelType, modelName, fixture);
465
+ return this.pushFixture(modelType, fixture);
466
+ } else {
467
+ return store.makeModel(modelType, fixture);
468
+ }
469
+ },
470
+ /**
471
+ Make a list of Fixtures
458
472
 
473
+ @param {String} name name of fixture
474
+ @param {Number} number number to create
475
+ @param {String} trait optional trait names ( one or more )
476
+ @param {Object} options optional fixture options that will override default fixture values
477
+ @returns {Array} list of json fixtures or records depending on the adapter type
478
+ */
479
+ makeList: function() {
480
+ Ember.assert("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures", this.store);
481
+
482
+ var arr = [];
483
+ var args = Array.prototype.slice.call(arguments);
484
+ Ember.assert("makeList needs at least 2 arguments, a name and a number",args.length >= 2);
485
+ var number = args.splice(1,1)[0];
486
+ Ember.assert("Second argument to makeList should be a number (of fixtures to make.)",typeof number == 'number');
487
+
488
+ for (var i = 0; i < number; i++) {
489
+ arr.push(this.make.apply(this, args));
490
+ }
491
+ return arr;
492
+ },
459
493
  /**
460
494
  Clear model instances from FIXTURES array, and from store cache.
461
495
  Reset the id sequence for the models back to zero.
@@ -543,30 +577,30 @@ var FactoryGuy = {
543
577
  return adapter instanceof DS.FixtureAdapter;
544
578
  },
545
579
  /**
546
- Make new fixture and save to store. If the store is using FixtureAdapter,
547
- will push to FIXTURE array, otherwise will use push method on adapter to load
548
- the record into the store
549
-
550
- @param {String} name fixture name
551
- @param {String} trait optional trait names ( one or more )
552
- @param {Object} opts optional fixture options that will override default fixture values
553
- @returns {Object|DS.Model} json or record depending on the adapter type
580
+ Deprecated in favor of FactoryGuy.make
554
581
  */
555
582
  makeFixture: function () {
556
- var store = this;
557
- var fixture = FactoryGuy.build.apply(FactoryGuy, arguments);
558
- var name = arguments[0];
559
- var modelName = FactoryGuy.lookupModelForFixtureName(name);
560
- var modelType = store.modelFor(modelName);
561
- if (this.usingFixtureAdapter()) {
562
- this.setAssociationsForFixtureAdapter(modelType, modelName, fixture);
563
- return FactoryGuy.pushFixture(modelType, fixture);
564
- } else {
565
- return store.makeModel(modelType, fixture);
566
- }
583
+ Ember.deprecate('DEPRECATION Warning: use FactoryGuy.make instead');
584
+ FactoryGuy.make.call(FactoryGuy, arguments)
585
+ },
586
+ /**
587
+ Deprecated in favor of FactoryGuy.makeList
588
+ */
589
+ makeList: function () {
590
+ Ember.deprecate('DEPRECATION Warning: use FactoryGuy.makeList instead');
591
+ FactoryGuy.makeList.call(FactoryGuy, arguments)
567
592
  },
593
+ /**
594
+ * Most of the work of making the model from the json fixture is going on here.
595
+ * @param modelType
596
+ * @param fixture
597
+ * @returns {*}
598
+ */
568
599
  makeModel: function (modelType, fixture) {
569
- var store = this, modelName = store.modelFor(modelType).typeKey, model;
600
+ var store = this,
601
+ modelName = store.modelFor(modelType).typeKey,
602
+ model;
603
+
570
604
  Em.run(function () {
571
605
  store.findEmbeddedAssociationsForRESTAdapter(modelType, fixture);
572
606
  if (fixture.type) {
@@ -580,22 +614,6 @@ var FactoryGuy = {
580
614
  });
581
615
  return model;
582
616
  },
583
- /**
584
- Make a list of Fixtures
585
-
586
- @param {String} name name of fixture
587
- @param {Number} number number to create
588
- @param {Object} options fixture options
589
- @returns {Array} list of json fixtures or records depending on the adapter type
590
- */
591
- makeList: function () {
592
- var arr = [];
593
- var number = arguments[1];
594
- for (var i = 0; i < number; i++) {
595
- arr.push(this.makeFixture.apply(this, arguments));
596
- }
597
- return arr;
598
- },
599
617
  /**
600
618
  Set the hasMany and belongsTo associations for FixtureAdapter.
601
619
 
@@ -812,11 +830,10 @@ var FactoryGuyTestMixin = Em.Mixin.create({
812
830
  return this.getStore().find(type, id);
813
831
  },
814
832
  /**
815
- Make new fixture and save to store. Proxy to store#makeFixture method
833
+ Make new fixture and save to store. Proxy to FactoryGuy#make method
816
834
  */
817
835
  make: function () {
818
- var store = this.getStore();
819
- return store.makeFixture.apply(store, arguments);
836
+ return FactoryGuy.make.apply(FactoryGuy, arguments);
820
837
  },
821
838
  getStore: function () {
822
839
  return this.get('container').lookup('store:main');
@@ -837,6 +854,9 @@ var FactoryGuyTestMixin = Em.Mixin.create({
837
854
  type: options.type || 'GET',
838
855
  status: options.status || 200
839
856
  };
857
+ if (options.urlParams) {
858
+ request.urlParams = options.urlParams;
859
+ }
840
860
  if (options.data) {
841
861
  request.data = options.data;
842
862
  }
@@ -863,9 +883,8 @@ var FactoryGuyTestMixin = Em.Mixin.create({
863
883
  @param {Object} opts optional fixture options
864
884
  */
865
885
  handleFindMany: function () {
866
- var store = this.getStore();
867
886
  // make the records and load them in the store
868
- store.makeList.apply(store, arguments);
887
+ FactoryGuy.makeList.apply(FactoryGuy, arguments);
869
888
  var name = arguments[0];
870
889
  var modelName = FactoryGuy.lookupModelForFixtureName(name);
871
890
  var responseJson = {};
@@ -873,7 +892,35 @@ var FactoryGuyTestMixin = Em.Mixin.create({
873
892
  var url = this.buildURL(modelName);
874
893
  // mock the ajax call, but return nothing, since the records will be
875
894
  // retrieved from the store where they were just loaded above
876
- this.stubEndpointForHttpRequest(url, responseJson, { type: 'GET' });
895
+ this.stubEndpointForHttpRequest(url, responseJson);
896
+ },
897
+ /**
898
+ Handling ajax GET for finding all records for a type of model with query parameters.
899
+
900
+ ```js
901
+ // First build json for the instances you want 'returned' in your query.
902
+ var usersJson = FactoryGuy.buildList('user', 2);
903
+
904
+ // Pass in the parameters you will search on ( in this case 'name' and 'age' ) as an array,
905
+ // in the second argument.
906
+ testHelper.handleFindQuery('user', ['name', 'age'], usersJson);
907
+
908
+ store.findQuery('user', {name:'Bob', age: 10}}).then(function(userInstances){
909
+ /// userInstances were created from the usersJson that you passed in
910
+ })
911
+ ```
912
+
913
+ The model instances will be created from the json you have passed in.
914
+
915
+ @param {String} modelName name of the mode like 'user' for User model type
916
+ @param {String} searchParams the parameters that will be queried
917
+ @param {Object} json fixture json used to build the resulting modelType instances
918
+ */
919
+ handleFindQuery: function (modelName, searchParams, json) {
920
+ var responseJson = {};
921
+ responseJson[modelName.pluralize()] = json;
922
+ var url = this.buildURL(modelName);
923
+ this.stubEndpointForHttpRequest(url, responseJson, {urlParams: searchParams});
877
924
  },
878
925
  /**
879
926
  Handling ajax POST ( create record ) for a model. You can mock