ember-data-factory-guy 0.9.2 → 0.9.3
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/README.md +38 -8
- data/bower.json +1 -1
- data/dist/amd/factory-guy.js +94 -20
- data/dist/ember-data-factory-guy.js +95 -21
- data/dist/ember-data-factory-guy.min.js +1 -1
- data/ember-data-factory-guy.gemspec +5 -1
- data/package.json +1 -1
- data/src/factory_guy.js +3 -1
- data/src/factory_guy_test_mixin.js +39 -13
- data/src/store.js +53 -7
- data/tests/factory_guy_test.js +1 -1
- data/tests/factory_guy_test_mixin_test.js +44 -6
- data/tests/fixture_adapter_factory_test.js +112 -60
- data/tests/index.html +1 -1
- data/tests/store_test.js +198 -0
- data/tests/support/factories/company_factory.js +4 -1
- data/tests/support/factories/property_factory.js +6 -1
- data/tests/support/factories/user_factory.js +3 -0
- data/tests/support/models/person.js +3 -1
- data/tests/support/models/user.js +1 -1
- data/tests/support/test_helper.js +3 -3
- data/tests/test_setup.js +17 -2
- data/vendor/assets/javascripts/ember_data_factory_guy.js +98 -23
- metadata +2 -2
@@ -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){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
|
+
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);fixture=FactoryGuy.pushFixture(modelType,fixture);store.loadModelForFixtureAdapter(modelType,fixture);return 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){var hasManyRelation,belongsToRecord;if(relationship.kind=="hasMany"){hasManyRelation=fixture[relationship.key];if(hasManyRelation){$.each(fixture[relationship.key],function(index,object){var id=object;if(Ember.typeOf(object)=="object"){FactoryGuy.pushFixture(relationship.type,object);id=object.id;hasManyRelation[index]=id}var hasManyfixtures=adapter.fixturesForType(relationship.type);var hasManyFixture=adapter.findFixtureById(hasManyfixtures,id);hasManyFixture[modelName]=fixture.id;self.loadModelForFixtureAdapter(relationship.type,hasManyFixture)})}}if(relationship.kind=="belongsTo"){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);self.loadModelForFixtureAdapter(relationship.type,belongsTofixture)}}})},loadModelForFixtureAdapter:function(modelType,fixture){var storeModel=this.getById(modelType,fixture.id),that=this;if(!Ember.isPresent(storeModel)||storeModel.get("isEmpty")){Ember.run(function(){var dup=Ember.copy(fixture,true);that.push(modelType,fixture);Ember.get(modelType,"relationshipsByName").forEach(function(relationship,name){if(fixture[relationship.key]){fixture[relationship.key]=dup[relationship.key]}})})}},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){var typeName,model;if(this.usingFixtureAdapter()){if(Ember.typeOf(type)==="string"&&Ember.isPresent(payload)&&Ember.isPresent(payload.id)){model=this.modelFor(type);FactoryGuy.pushFixture(model,payload);this.push(model,Ember.copy(payload,true))}else if(Ember.typeOf(type)==="object"||Ember.typeOf(payload)==="object"){if(Ember.isBlank(payload)){payload=type}for(var prop in payload){typeName=Ember.String.camelize(Ember.String.singularize(prop));model=this.modelFor(typeName);this.pushMany(model,Ember.makeArray(Ember.copy(payload[prop],true)));Ember.ArrayPolyfills.forEach.call(Ember.makeArray(payload[prop]),function(hash){FactoryGuy.pushFixture(model,hash)},this)}}else{throw new Ember.Error("Assertion Failed: You cannot use `store#pushPayload` with this method signature pushPayload("+type+","+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(){var records=FactoryGuy.makeList.apply(FactoryGuy,arguments);var name=arguments[0];var modelName=FactoryGuy.lookupModelForFixtureName(name);var responseJson={};var json=records.map(function(record){return record.toJSON({includeId:true})});responseJson[modelName.pluralize()]=json;var url=this.buildURL(modelName);this.stubEndpointForHttpRequest(url,responseJson)},handleFindQuery:function(modelName,searchParams,records){Ember.assert("The second argument of searchParams must be an array",Em.typeOf(searchParams)=="array");if(records){Ember.assert("The third argument ( records ) must be an array - found type:"+Em.typeOf(records),Em.typeOf(records)=="array")}else{records=[]}var json=records.map(function(record){return record.toJSON({includeId:true})});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,11 @@
|
|
1
1
|
# -*- encoding: utf-8 -*-
|
2
|
+
require 'json'
|
3
|
+
|
4
|
+
package = JSON.parse(File.read('package.json'))
|
5
|
+
|
2
6
|
Gem::Specification.new do |s|
|
3
7
|
s.name = "ember-data-factory-guy"
|
4
|
-
s.version = "
|
8
|
+
s.version = package["version"]
|
5
9
|
s.platform = Gem::Platform::RUBY
|
6
10
|
s.authors = ["Daniel Sudol", "Alex Opak"]
|
7
11
|
s.email = ["dansudol@yahoo.com", "opak.alexandr@gmail.com"]
|
data/package.json
CHANGED
data/src/factory_guy.js
CHANGED
@@ -284,7 +284,9 @@ var FactoryGuy = {
|
|
284
284
|
|
285
285
|
if (store.usingFixtureAdapter()) {
|
286
286
|
store.setAssociationsForFixtureAdapter(modelType, modelName, fixture);
|
287
|
-
|
287
|
+
fixture = FactoryGuy.pushFixture(modelType, fixture);
|
288
|
+
store.loadModelForFixtureAdapter(modelType, fixture);
|
289
|
+
return fixture;
|
288
290
|
} else {
|
289
291
|
return store.makeModel(modelType, fixture);
|
290
292
|
}
|
@@ -77,6 +77,17 @@ var FactoryGuyTestMixin = Em.Mixin.create({
|
|
77
77
|
Handling ajax GET for finding all records for a type of model.
|
78
78
|
You can mock failed find by passing in success argument as false.
|
79
79
|
|
80
|
+
```js
|
81
|
+
// Pass in the parameters you would normally pass into FactoryGuy.makeList,
|
82
|
+
// like fixture name, number of fixtures to make, and optional traits,
|
83
|
+
// or fixture options
|
84
|
+
testHelper.handleFindMany('user', 2, 'with_hats');
|
85
|
+
|
86
|
+
store.find('user').then(function(users){
|
87
|
+
|
88
|
+
});
|
89
|
+
```
|
90
|
+
|
80
91
|
@param {String} name name of the fixture ( or model ) to find
|
81
92
|
@param {Number} number number of fixtures to create
|
82
93
|
@param {String} trait optional traits (one or more)
|
@@ -84,39 +95,54 @@ var FactoryGuyTestMixin = Em.Mixin.create({
|
|
84
95
|
*/
|
85
96
|
handleFindMany: function () {
|
86
97
|
// make the records and load them in the store
|
87
|
-
FactoryGuy.makeList.apply(FactoryGuy, arguments);
|
98
|
+
var records = FactoryGuy.makeList.apply(FactoryGuy, arguments);
|
88
99
|
var name = arguments[0];
|
89
100
|
var modelName = FactoryGuy.lookupModelForFixtureName(name);
|
90
101
|
var responseJson = {};
|
91
|
-
|
102
|
+
var json = records.map(function(record) {return record.toJSON({includeId: true})});
|
103
|
+
responseJson[modelName.pluralize()] = json;
|
92
104
|
var url = this.buildURL(modelName);
|
93
|
-
// mock the ajax call, but return nothing, since the records will be
|
94
|
-
// retrieved from the store where they were just loaded above
|
95
105
|
this.stubEndpointForHttpRequest(url, responseJson);
|
96
106
|
},
|
97
107
|
/**
|
98
108
|
Handling ajax GET for finding all records for a type of model with query parameters.
|
99
109
|
|
110
|
+
First variation = pass in model instances
|
100
111
|
```js
|
101
|
-
// First build json for the instances you want 'returned' in your query.
|
102
|
-
var usersJson = FactoryGuy.buildList('user', 2);
|
103
112
|
|
104
|
-
//
|
105
|
-
|
106
|
-
|
113
|
+
// Create model instances
|
114
|
+
var users = FactoryGuy.makeList('user', 2, 'with_hats');
|
115
|
+
|
116
|
+
// Pass in the array of model instances as last argument
|
117
|
+
testHelper.handleFindQuery('user', ['name', 'age'], users);
|
107
118
|
|
108
119
|
store.findQuery('user', {name:'Bob', age: 10}}).then(function(userInstances){
|
109
|
-
/// userInstances
|
120
|
+
/// userInstances will be the same of the users that were passed in
|
110
121
|
})
|
111
122
|
```
|
112
123
|
|
113
|
-
|
124
|
+
Third variation - pass in nothing for last argument
|
125
|
+
```js
|
126
|
+
// This simulates a query that returns no results
|
127
|
+
testHelper.handleFindQuery('user', ['age']);
|
128
|
+
|
129
|
+
store.findQuery('user', {age: 10000}}).then(function(userInstances){
|
130
|
+
/// userInstances will be empty
|
131
|
+
})
|
132
|
+
```
|
114
133
|
|
115
134
|
@param {String} modelName name of the mode like 'user' for User model type
|
116
135
|
@param {String} searchParams the parameters that will be queried
|
117
|
-
@param {
|
136
|
+
@param {Array} array of DS.Model records to be 'returned' by query
|
118
137
|
*/
|
119
|
-
handleFindQuery: function (modelName, searchParams,
|
138
|
+
handleFindQuery: function (modelName, searchParams, records) {
|
139
|
+
Ember.assert('The second argument of searchParams must be an array',Em.typeOf(searchParams) == 'array')
|
140
|
+
if (records) {
|
141
|
+
Ember.assert('The third argument ( records ) must be an array - found type:' + Em.typeOf(records), Em.typeOf(records) == 'array')
|
142
|
+
} else {
|
143
|
+
records = []
|
144
|
+
}
|
145
|
+
var json = records.map(function(record) {return record.toJSON({includeId: true})})
|
120
146
|
var responseJson = {};
|
121
147
|
responseJson[modelName.pluralize()] = json;
|
122
148
|
var url = this.buildURL(modelName);
|
data/src/store.js
CHANGED
@@ -25,7 +25,7 @@
|
|
25
25
|
* Most of the work of making the model from the json fixture is going on here.
|
26
26
|
* @param modelType
|
27
27
|
* @param fixture
|
28
|
-
* @returns {
|
28
|
+
* @returns {DS.Model} instance of DS.Model
|
29
29
|
*/
|
30
30
|
makeModel: function (modelType, fixture) {
|
31
31
|
var store = this,
|
@@ -74,9 +74,11 @@
|
|
74
74
|
setAssociationsForFixtureAdapter: function (modelType, modelName, fixture) {
|
75
75
|
var self = this;
|
76
76
|
var adapter = this.adapterFor('application');
|
77
|
+
|
77
78
|
Ember.get(modelType, 'relationshipsByName').forEach(function (relationship, name) {
|
79
|
+
var hasManyRelation, belongsToRecord;
|
78
80
|
if (relationship.kind == 'hasMany') {
|
79
|
-
|
81
|
+
hasManyRelation = fixture[relationship.key];
|
80
82
|
if (hasManyRelation) {
|
81
83
|
$.each(fixture[relationship.key], function (index, object) {
|
82
84
|
// used to require that the relationship was set by id,
|
@@ -84,17 +86,19 @@
|
|
84
86
|
// normalize that back to the id
|
85
87
|
var id = object;
|
86
88
|
if (Ember.typeOf(object) == 'object') {
|
89
|
+
FactoryGuy.pushFixture(relationship.type, object);
|
87
90
|
id = object.id;
|
88
91
|
hasManyRelation[index] = id;
|
89
92
|
}
|
90
93
|
var hasManyfixtures = adapter.fixturesForType(relationship.type);
|
91
|
-
var
|
92
|
-
|
94
|
+
var hasManyFixture = adapter.findFixtureById(hasManyfixtures, id);
|
95
|
+
hasManyFixture[modelName] = fixture.id;
|
96
|
+
self.loadModelForFixtureAdapter(relationship.type, hasManyFixture);
|
93
97
|
});
|
94
98
|
}
|
95
99
|
}
|
96
100
|
if (relationship.kind == 'belongsTo') {
|
97
|
-
|
101
|
+
belongsToRecord = fixture[relationship.key];
|
98
102
|
if (belongsToRecord) {
|
99
103
|
if (typeof belongsToRecord == 'object') {
|
100
104
|
FactoryGuy.pushFixture(relationship.type, belongsToRecord);
|
@@ -107,10 +111,29 @@
|
|
107
111
|
belongsTofixture[hasManyName] = [];
|
108
112
|
}
|
109
113
|
belongsTofixture[hasManyName].push(fixture.id);
|
114
|
+
self.loadModelForFixtureAdapter(relationship.type, belongsTofixture);
|
110
115
|
}
|
111
116
|
}
|
112
117
|
});
|
113
118
|
},
|
119
|
+
|
120
|
+
loadModelForFixtureAdapter: function(modelType, fixture) {
|
121
|
+
var storeModel = this.getById(modelType, fixture.id),
|
122
|
+
that = this;
|
123
|
+
if (!Ember.isPresent(storeModel) || storeModel.get('isEmpty')) {
|
124
|
+
Ember.run(function () {
|
125
|
+
var dup = Ember.copy(fixture, true);
|
126
|
+
that.push(modelType, fixture);
|
127
|
+
//replace relationships back to ids instead of built ember objects
|
128
|
+
Ember.get(modelType, 'relationshipsByName').forEach(function (relationship, name) {
|
129
|
+
if(fixture[relationship.key]) {
|
130
|
+
fixture[relationship.key] = dup[relationship.key];
|
131
|
+
}
|
132
|
+
});
|
133
|
+
});
|
134
|
+
}
|
135
|
+
},
|
136
|
+
|
114
137
|
/**
|
115
138
|
Before pushing the fixture to the store, do some preprocessing. Descend into the tree
|
116
139
|
of object data, and convert child objects to record instances recursively.
|
@@ -219,9 +242,32 @@
|
|
219
242
|
@param {Object} payload
|
220
243
|
*/
|
221
244
|
pushPayload: function (type, payload) {
|
245
|
+
var typeName, model;
|
246
|
+
|
222
247
|
if (this.usingFixtureAdapter()) {
|
223
|
-
|
224
|
-
|
248
|
+
if (Ember.typeOf(type) === 'string' && Ember.isPresent(payload) && Ember.isPresent(payload.id)){
|
249
|
+
//pushPayload('user', {id:..})
|
250
|
+
model = this.modelFor(type);
|
251
|
+
FactoryGuy.pushFixture(model, payload);
|
252
|
+
this.push(model, Ember.copy(payload, true));
|
253
|
+
} else if(Ember.typeOf(type) === 'object' || Ember.typeOf(payload) === 'object') {
|
254
|
+
//pushPayload({users: {id:..}}) OR pushPayload('user', {users: {id:..}})
|
255
|
+
if(Ember.isBlank(payload)){
|
256
|
+
payload = type;
|
257
|
+
}
|
258
|
+
|
259
|
+
for (var prop in payload) {
|
260
|
+
typeName = Ember.String.camelize(Ember.String.singularize(prop));
|
261
|
+
model = this.modelFor(typeName);
|
262
|
+
|
263
|
+
this.pushMany(model, Ember.makeArray( Ember.copy(payload[prop], true) ));
|
264
|
+
Ember.ArrayPolyfills.forEach.call(Ember.makeArray(payload[prop]), function(hash) {
|
265
|
+
FactoryGuy.pushFixture(model, hash);
|
266
|
+
}, this);
|
267
|
+
}
|
268
|
+
} else {
|
269
|
+
throw new Ember.Error('Assertion Failed: You cannot use `store#pushPayload` with this method signature pushPayload(' + type + ',' + payload + ')');
|
270
|
+
}
|
225
271
|
} else {
|
226
272
|
this._super(type, payload);
|
227
273
|
}
|
data/tests/factory_guy_test.js
CHANGED
@@ -14,7 +14,7 @@ module('FactoryGuy with DS.RESTAdapter', {
|
|
14
14
|
|
15
15
|
test("can set and get store", function() {
|
16
16
|
FactoryGuy.setStore(store);
|
17
|
-
|
17
|
+
ok(FactoryGuy.getStore() == store)
|
18
18
|
});
|
19
19
|
|
20
20
|
test("Using sequences in definitions", function() {
|
@@ -56,14 +56,52 @@ asyncTest("#handleCreate the basic", function() {
|
|
56
56
|
|
57
57
|
/////// handleFindQuery //////////
|
58
58
|
|
59
|
-
|
60
|
-
|
59
|
+
test("#handleFindQuery second argument should be an array", function(assert) {
|
60
|
+
assert.throws(function(){testHelper.handleFindQuery('user', 'name', {})},"second argument not correct type");
|
61
|
+
});
|
62
|
+
|
63
|
+
test("#handleFindQuery json payload argument should be an array", function(assert) {
|
64
|
+
assert.throws(function(){testHelper.handleFindQuery('user', ['name'], {})},"payload argument is not an array");
|
65
|
+
});
|
66
|
+
|
67
|
+
asyncTest("#handleFindQuery passing in nothing as last argument returns no results", function() {
|
68
|
+
testHelper.handleFindQuery('user', ['name']);
|
69
|
+
store.findQuery('user', {name: 'Bob'}).then(function (users) {
|
70
|
+
equal(users.get('length'),0)
|
71
|
+
start()
|
72
|
+
});
|
73
|
+
})
|
74
|
+
|
75
|
+
|
76
|
+
asyncTest("#handleFindQuery passing in existing instances returns those and does not create new ones", function() {
|
77
|
+
var users = FactoryGuy.makeList('user', 2, 'with_hats');
|
61
78
|
testHelper.handleFindQuery('user', ['name'], users);
|
62
79
|
|
80
|
+
equal(store.all('user').get('content.length'), 2, 'start out with 2 instances')
|
81
|
+
|
63
82
|
store.findQuery('user', {name: 'Bob'}).then(function (users) {
|
64
83
|
equal(users.get('length'), 2)
|
65
84
|
equal(users.get('firstObject.name'), 'User1')
|
85
|
+
equal(users.get('firstObject.hats.length'), 2)
|
66
86
|
equal(users.get('lastObject.name'), 'User2')
|
87
|
+
equal(store.all('user').get('content.length'), 2, 'no new instances created')
|
88
|
+
start();
|
89
|
+
})
|
90
|
+
});
|
91
|
+
|
92
|
+
asyncTest("#handleFindQuery passing in existing instances with hasMany and belongsTo", function() {
|
93
|
+
var users = FactoryGuy.makeList('company', 2, 'with_projects', 'with_profile');
|
94
|
+
testHelper.handleFindQuery('company', ['name'], users);
|
95
|
+
|
96
|
+
equal(store.all('company').get('content.length'), 2, 'start out with 2 instances')
|
97
|
+
|
98
|
+
store.findQuery('company', {name: 'Dude'}).then(function (companies) {
|
99
|
+
equal(companies.get('length'), 2)
|
100
|
+
ok(companies.get('firstObject.profile') instanceof Profile)
|
101
|
+
equal(companies.get('firstObject.projects.length'), 2)
|
102
|
+
ok(companies.get('lastObject.profile') instanceof Profile)
|
103
|
+
equal(companies.get('lastObject.projects.length'), 2)
|
104
|
+
equal(store.all('company').get('content.length'), 2, 'no new instances created')
|
67
105
|
start();
|
68
106
|
})
|
69
107
|
});
|
@@ -74,7 +112,7 @@ asyncTest("#handleFindQuery", function() {
|
|
74
112
|
asyncTest("#handleFindMany the basic", function () {
|
75
113
|
testHelper.handleFindMany('profile', 2);
|
76
114
|
|
77
|
-
store.
|
115
|
+
store.findAll('profile').then(function (profiles) {
|
78
116
|
ok(profiles.get('length') == 2);
|
79
117
|
start();
|
80
118
|
});
|
@@ -83,7 +121,7 @@ asyncTest("#handleFindMany the basic", function () {
|
|
83
121
|
asyncTest("#handleFindMany with fixture options", function () {
|
84
122
|
testHelper.handleFindMany('profile', 2, {description: 'dude'});
|
85
123
|
|
86
|
-
store.
|
124
|
+
store.findAll('profile').then(function (profiles) {
|
87
125
|
ok(profiles.get('length') == 2);
|
88
126
|
ok(profiles.get('firstObject.description') == 'dude');
|
89
127
|
start();
|
@@ -93,7 +131,7 @@ asyncTest("#handleFindMany with fixture options", function () {
|
|
93
131
|
asyncTest("#handleFindMany with traits", function () {
|
94
132
|
testHelper.handleFindMany('profile', 2, 'goofy_description');
|
95
133
|
|
96
|
-
store.
|
134
|
+
store.findAll('profile').then(function (profiles) {
|
97
135
|
ok(profiles.get('length') == 2);
|
98
136
|
ok(profiles.get('firstObject.description') == 'goofy');
|
99
137
|
start();
|
@@ -103,7 +141,7 @@ asyncTest("#handleFindMany with traits", function () {
|
|
103
141
|
asyncTest("#handleFindMany with traits and extra options", function () {
|
104
142
|
testHelper.handleFindMany('profile', 2, 'goofy_description', {description: 'dude'});
|
105
143
|
|
106
|
-
store.
|
144
|
+
store.findAll('profile').then(function (profiles) {
|
107
145
|
ok(profiles.get('length') == 2);
|
108
146
|
ok(profiles.get('firstObject.description') == 'dude');
|
109
147
|
start();
|
@@ -25,7 +25,8 @@ test("#pushFixture adds fixture to Fixture array on model", function () {
|
|
25
25
|
|
26
26
|
|
27
27
|
asyncTest("can change fixture attributes after creation", function () {
|
28
|
-
var user =
|
28
|
+
var user = FactoryGuy.make('user');
|
29
|
+
notEqual(user.name, 'new name');
|
29
30
|
user.name = "new name";
|
30
31
|
|
31
32
|
store.find('user', 1).then(function (user) {
|
@@ -36,21 +37,27 @@ asyncTest("can change fixture attributes after creation", function () {
|
|
36
37
|
|
37
38
|
|
38
39
|
test("#resetModels clears the store of models, clears the FIXTURES arrays for each model and resets the model definition", function () {
|
39
|
-
var project =
|
40
|
-
var user =
|
40
|
+
var project = FactoryGuy.make('project');
|
41
|
+
var user = FactoryGuy.make('user', { projects: [project] });
|
41
42
|
|
42
43
|
for (model in FactoryGuy.modelDefinitions) {
|
43
44
|
var definition = FactoryGuy.modelDefinitions[model];
|
44
45
|
sinon.spy(definition, 'reset');
|
45
46
|
}
|
46
47
|
|
48
|
+
equal(User.FIXTURES.length, 1);
|
49
|
+
equal(Project.FIXTURES.length, 1);
|
50
|
+
|
51
|
+
equal(store.all('user').get('length'), 1);
|
52
|
+
equal(store.all('project').get('length'), 1);
|
53
|
+
|
47
54
|
FactoryGuy.resetModels(store);
|
48
55
|
|
49
56
|
equal(User.FIXTURES.length, 0);
|
50
57
|
equal(Project.FIXTURES.length, 0);
|
51
58
|
|
52
|
-
equal(store.all('user').get('
|
53
|
-
equal(store.all('project').get('
|
59
|
+
equal(store.all('user').get('length'), 0);
|
60
|
+
equal(store.all('project').get('length'), 0);
|
54
61
|
|
55
62
|
for (model in FactoryGuy.modelDefinitions) {
|
56
63
|
var definition = FactoryGuy.modelDefinitions[model];
|
@@ -59,6 +66,16 @@ test("#resetModels clears the store of models, clears the FIXTURES arrays for ea
|
|
59
66
|
}
|
60
67
|
});
|
61
68
|
|
69
|
+
test("Confirm traits build relationships", function () {
|
70
|
+
var project = FactoryGuy.make('project', 'big'),
|
71
|
+
projectWithUser = FactoryGuy.make('project_with_admin');
|
72
|
+
|
73
|
+
equal(Project.FIXTURES.length, 2);
|
74
|
+
equal(User.FIXTURES.length, 1);
|
75
|
+
|
76
|
+
equal(project.title, 'Big Project', 'Big trait changed name to "Big Project"');
|
77
|
+
equal(projectWithUser.user, 1, 'User created');
|
78
|
+
});
|
62
79
|
|
63
80
|
module('DS.Store with DS.FixtureAdapter', {
|
64
81
|
setup: function () {
|
@@ -73,71 +90,106 @@ module('DS.Store with DS.FixtureAdapter', {
|
|
73
90
|
});
|
74
91
|
|
75
92
|
|
76
|
-
test("#
|
77
|
-
var json =
|
93
|
+
test("#make builds and pushes fixture into the models FIXTURE array", function () {
|
94
|
+
var json = FactoryGuy.make('user');
|
78
95
|
equal(User.FIXTURES.length, 1);
|
79
96
|
equal(User.FIXTURES[0], json);
|
80
97
|
});
|
81
98
|
|
82
|
-
|
83
|
-
|
84
|
-
var p1 = store.makeFixture('project');
|
99
|
+
asyncTest("#make sets belongsTo on hasMany associations", function () {
|
100
|
+
var p1 = FactoryGuy.make('project');
|
85
101
|
// second project not added on purpose to make sure only one is
|
86
102
|
// assigned in hasMany
|
87
|
-
|
88
|
-
var user =
|
103
|
+
FactoryGuy.make('project');
|
104
|
+
var user = FactoryGuy.make('user', {projects: [p1]})
|
89
105
|
|
90
106
|
store.find('user', 1).then(function (user) {
|
91
|
-
|
92
|
-
|
93
|
-
// console.log(user+'', projects)
|
94
|
-
// equal(projects.length, 1, "adds hasMany records");
|
107
|
+
var projects = user.get('projects');
|
108
|
+
equal(projects.get('length'), 1, "adds hasMany records");
|
95
109
|
start();
|
96
|
-
})
|
97
|
-
})
|
98
|
-
|
110
|
+
});
|
111
|
+
});
|
99
112
|
|
100
|
-
asyncTest("#
|
101
|
-
var userJson =
|
102
|
-
var projectJson =
|
113
|
+
asyncTest("#make adds record to hasMany association array for which it belongsTo", function () {
|
114
|
+
var userJson = FactoryGuy.make('user');
|
115
|
+
var projectJson = FactoryGuy.make('project', { user: userJson });
|
103
116
|
|
104
117
|
store.find('user', userJson.id).then(function (user) {
|
105
118
|
var projects = user.get('projects');
|
106
|
-
equal(projects.length, 1, "adds hasMany records");
|
107
|
-
|
119
|
+
equal(projects.get('length'), 1, "adds hasMany records");
|
120
|
+
ok(projects.get('firstObject.user') == user, "sets belongsTo record");
|
108
121
|
start();
|
109
|
-
})
|
110
|
-
})
|
122
|
+
});
|
123
|
+
});
|
111
124
|
|
112
|
-
asyncTest("#
|
113
|
-
var projectWithUser =
|
125
|
+
asyncTest("#make handles traits declaring belongsTo associations in fixture", function () {
|
126
|
+
var projectWithUser = FactoryGuy.make('project_with_user');
|
127
|
+
equal(Project.FIXTURES.length, 1);
|
114
128
|
equal(User.FIXTURES.length, 1);
|
115
129
|
|
116
130
|
store.find('user', 1).then(function (user) {
|
117
|
-
|
118
131
|
var projects = user.get('projects');
|
119
|
-
|
132
|
+
|
133
|
+
equal(projects.get('length'), 1, "adds hasMany records");
|
134
|
+
equal(projects.get('firstObject.id'), projectWithUser.id);
|
120
135
|
equal(projects.get('firstObject.user.id'), 1, "sets belongsTo record");
|
121
136
|
start();
|
122
|
-
})
|
123
|
-
|
124
|
-
|
125
|
-
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
// console.log('c',user.toJSON())
|
130
|
-
// })
|
131
|
-
// start();
|
132
|
-
// })
|
133
|
-
})
|
137
|
+
});
|
138
|
+
});
|
139
|
+
|
140
|
+
asyncTest("#make handles primary belongsTo association in fixture", function () {
|
141
|
+
var projectWithUser = FactoryGuy.make('project_with_user');
|
142
|
+
equal(Project.FIXTURES.length, 1);
|
143
|
+
equal(User.FIXTURES.length, 1);
|
134
144
|
|
145
|
+
store.find('project', projectWithUser.id).then( function(project) {
|
146
|
+
var user = project.get('user');
|
147
|
+
ok(user);
|
148
|
+
equal(user.get('id'), projectWithUser.user);
|
149
|
+
equal(user.get('projects.firstObject.id'), projectWithUser.id)
|
150
|
+
|
151
|
+
start();
|
152
|
+
});
|
153
|
+
});
|
154
|
+
|
155
|
+
asyncTest('#make handles hasMany association in fixture', function () {
|
156
|
+
var userWithProjects = FactoryGuy.make('user', 'with_projects');
|
157
|
+
equal(Project.FIXTURES.length, 2);
|
158
|
+
equal(User.FIXTURES.length, 1);
|
159
|
+
|
160
|
+
store.find('user', userWithProjects.id).then(function(user) {
|
161
|
+
var projects = user.get('projects');
|
162
|
+
equal(user.get('id'), userWithProjects.id);
|
163
|
+
equal(projects.get('length'), 2);
|
164
|
+
deepEqual(
|
165
|
+
projects.mapBy('id').sort(),
|
166
|
+
userWithProjects.projects.map(function(project){ return project.toString(); }).sort()
|
167
|
+
);
|
168
|
+
|
169
|
+
start();
|
170
|
+
});
|
171
|
+
});
|
172
|
+
|
173
|
+
// TODO:: does not handle deeply embedded relationships yet..
|
174
|
+
// asyncTest('#make handles belongsTo deeply associated in fixture', function () {
|
175
|
+
// var propertyOwnersProjects = FactoryGuy.make('property', 'with_owners_with_projects');
|
176
|
+
// equal(Property.FIXTURES.length, 1);
|
177
|
+
// equal(User.FIXTURES.length, 2);
|
178
|
+
// equal(Project.FIXTURES.length, 4);
|
179
|
+
//
|
180
|
+
// store.find('property', propertyOwnersProjects.id).then(function(property) {
|
181
|
+
// var users = property.get('owners');
|
182
|
+
// users.each(function(user){
|
183
|
+
// user.get('projects');
|
184
|
+
// });
|
185
|
+
// start();
|
186
|
+
// });
|
187
|
+
// });
|
135
188
|
|
136
189
|
asyncTest("#createRecord adds belongsTo association to records it hasMany of", function () {
|
137
|
-
var user =
|
190
|
+
var user = FactoryGuy.make('user');
|
138
191
|
|
139
192
|
store.find('user', user.id).then(function (user) {
|
140
|
-
|
141
193
|
var projectJson = {title: 'project', user: user};
|
142
194
|
|
143
195
|
store.createRecord('project', projectJson).save()
|
@@ -145,18 +197,18 @@ asyncTest("#createRecord adds belongsTo association to records it hasMany of", f
|
|
145
197
|
return Ember.RSVP.all([project.get('user'), user.get('projects')]);
|
146
198
|
}).then(function (promises) {
|
147
199
|
var projectUser = promises[0], projects = promises[1];
|
148
|
-
|
149
|
-
|
200
|
+
|
201
|
+
ok(projectUser == user);
|
202
|
+
equal(projects.get('length'), 1);
|
150
203
|
start();
|
151
204
|
});
|
152
|
-
})
|
153
|
-
})
|
205
|
+
});
|
206
|
+
});
|
154
207
|
|
155
208
|
asyncTest("#createRecord can work for one-to-none associations", function () {
|
156
|
-
var user =
|
209
|
+
var user = FactoryGuy.make('user');
|
157
210
|
|
158
211
|
store.find('user', user.id).then(function (user) {
|
159
|
-
|
160
212
|
var smallCompanyJson = {name: 'small company', owner: user};
|
161
213
|
|
162
214
|
store.createRecord('small_company', smallCompanyJson).save()
|
@@ -166,20 +218,20 @@ asyncTest("#createRecord can work for one-to-none associations", function () {
|
|
166
218
|
equal(owner.get('id'), user.get('id'));
|
167
219
|
start();
|
168
220
|
});
|
169
|
-
})
|
170
|
-
})
|
221
|
+
});
|
222
|
+
});
|
171
223
|
|
172
224
|
asyncTest("#createRecord adds hasMany association to records it hasMany of ", function () {
|
173
|
-
var usersJson =
|
174
|
-
var userPromises = usersJson.map(function(json) { return store.find('user', json.id) })
|
175
|
-
Em.RSVP.all(userPromises).then(function (users) {
|
225
|
+
var usersJson = FactoryGuy.makeList('user', 3);
|
226
|
+
var userPromises = usersJson.map(function(json) { return store.find('user', json.id) });
|
176
227
|
|
177
|
-
|
228
|
+
Ember.RSVP.all(userPromises).then(function (users) {
|
229
|
+
var propertyJson = {name: 'beach front property'},
|
230
|
+
property = store.createRecord('property', propertyJson),
|
231
|
+
owners = property.get('owners');
|
178
232
|
|
179
|
-
var property = store.createRecord('property', propertyJson);
|
180
|
-
var owners = property.get('owners')
|
181
233
|
owners.addObjects(users);
|
182
234
|
equal(users.get('length'), usersJson.length);
|
183
235
|
start();
|
184
|
-
})
|
185
|
-
})
|
236
|
+
});
|
237
|
+
});
|