ember-data-factory-guy 0.9.5 → 0.9.6

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 6abc061f668dd5d677abe7b0ec4f559d16af91f9
4
- data.tar.gz: 2d38bdb9f7f4f5255609cf8fe42f49f88d9857da
3
+ metadata.gz: 144fe2b151234c1c12f5fbc7c65ec2b10041a9cc
4
+ data.tar.gz: 2bce284e264f02e5fe52b7873e547b8269054d48
5
5
  SHA512:
6
- metadata.gz: 8cb599906cc1ce6ed367506f141aebaf405676142d34ee85984e3d76c85e167586a47abb8ffc30ae5e859e8eca1343930b4109f51436103478cebe203a34fc43
7
- data.tar.gz: 9969fb77e5903fe169847c9bb741073194222b4e5fb92c1071df6fe17606e51a5d9a24b3e75f5e67e74b41aeb7da6b1d171d3da7811e88ade8a40674fe4f6de7
6
+ metadata.gz: ab291d9acdf10c07f817e3e1472001e85dfff454b9f5e58b1708b358b2f8a0f1105e8891030ddc89fd710523c82a90b14324d717bf549c717558efedd264bfa5
7
+ data.tar.gz: 625aaea6c2fbc4098cd96855605ec34a5cd13a51b9d38b6c777cd8b6775dc7bdabb626d800ce4537037fe463ed2989f2dd47ea9bc3af816b90bd375a2b0d9461
data/Gruntfile.js CHANGED
@@ -10,6 +10,7 @@ module.exports = function(grunt) {
10
10
  'src/sequence.js',
11
11
  'src/model_definition.js',
12
12
  'src/factory_guy.js',
13
+ 'src/mock_create_request.js',
13
14
  'src/store.js',
14
15
  'src/factory_guy_test_mixin.js',
15
16
  ],
@@ -21,6 +22,7 @@ module.exports = function(grunt) {
21
22
  'src/sequence.js',
22
23
  'src/model_definition.js',
23
24
  'src/factory_guy.js',
25
+ 'src/mock_create_request.js',
24
26
  'src/store.js',
25
27
  'src/factory_guy_test_mixin.js',
26
28
  'src/epilogue.js'
data/README.md CHANGED
@@ -10,7 +10,7 @@ of ember-data-factory-guy.
10
10
  - 0.6.4 -> ember-data-1.0.0-beta.8 and under
11
11
  - 0.7.1.1 -> ember-data-1.0.0-beta.10
12
12
  - 0.8.6 -> ember-data-1.0.0-beta.11
13
- - 0.9.4 -> ember-data-1.0.0-beta.12
13
+ - 0.9.5 -> ember-data-1.0.0-beta.12
14
14
 
15
15
  **Waiting for ember-data-1.0.0-beta.15 to make upgrade release, since there are a few issues with
16
16
  ember-data-1.0.0-beta.14.1 that make it difficult to use**
@@ -42,7 +42,7 @@ gem 'ember-data-factory-guy', group: test
42
42
  or for particular version:
43
43
 
44
44
  ```ruby
45
- gem 'ember-data-factory-guy', '0.9.4', group: test
45
+ gem 'ember-data-factory-guy', '0.9.5', group: test
46
46
  ```
47
47
 
48
48
  then:
@@ -77,7 +77,7 @@ or for particular version:
77
77
  "dependencies": {
78
78
  "foo-dependency": "latest",
79
79
  "other-foo-dependency": "latest",
80
- "ember-data-factory-guy": "0.9.4"
80
+ "ember-data-factory-guy": "0.9.5"
81
81
  }
82
82
  ```
83
83
 
@@ -102,7 +102,7 @@ The preferred way to use this project is to use the default adapter for your pro
102
102
  which is usually going to be the RESTAdapter/ActiveModelAdapter.
103
103
  *In other words, it is NOT recommended to use the DS.FixtureAdapter.*
104
104
 
105
- When you call: store.makeFixture('user'), you create model in the store and this method
105
+ When you call: FactoryGuy.make('user'), you create model in the store and this method
106
106
  returns this model instance
107
107
 
108
108
  *Since you are synchronously getting model instances, you can immediately start asking
@@ -567,11 +567,11 @@ module('User Model', {
567
567
  // Assumes the application's namespace is App, though yours may not be.
568
568
  testHelper = TestHelper.setup(App);
569
569
  store = testHelper.getStore();
570
- // You could at this point, make fixtures with testHelper.make,
570
+ // You could at this point, make fixtures with FactoryGuy.make,
571
571
  // but to be even more concise try this shortcut method to your tests
572
- make = testHelper.make.bind(testHelper)
572
+ make = FactoryGuy.make.bind(FactoryGuy)
573
573
  // or if your running in phantomjs and it does not support bind method try this:
574
- // make = function() {return testHelper.make.apply(testHelper,arguments)}
574
+ // make = function() {return FactoryGuy.make.apply(FactoryGuy,arguments)}
575
575
  },
576
576
  teardown: function() {
577
577
  Em.run(function() { testHelper.teardown(); });
@@ -593,7 +593,7 @@ test("make a user using your applications default adapter", function() {
593
593
  ### Integration Tests
594
594
 
595
595
 
596
- #### Using FactoryGuyTestMixin
596
+ ##### With FactoryGuyTestMixin
597
597
 
598
598
  - Uses mockjax
599
599
  - Has helper methods
@@ -609,10 +609,10 @@ FactoryGuyTestMixin assumes you will want to use that adapter to do your integra
609
609
 
610
610
  To do that you will still have to deal with ember data trying to create, update or delete records.
611
611
 
612
- If you put models into the store ( with store#makeFixture ), the http GET call does not need to be mocked,
612
+ If you put models into the store ( with FactoryGuy#make ), the http GET call does not need to be mocked,
613
613
  since that model is already in the store.
614
614
 
615
- But what if you want to handle create, update, and delete? Or even findAll records?
615
+ But what if you want to handle create, update, and delete? Or even reload or findAll records?
616
616
 
617
617
  FactoryGuy assumes you want to mock ajax calls with the mockjax library,
618
618
  and this is already bundled for you when you use the ember-data-factory-guy library.
@@ -624,7 +624,7 @@ tests run as shown in the previous section (Using FactoryGuyTestMixin)**
624
624
 
625
625
  ##### handleFindAll
626
626
  - for dealing with finding all records of a particular type
627
- - handleFindMany ( deprecated alias )
627
+ - handleFindMany is a deprecated alias for handleFindAll
628
628
 
629
629
  ```javascript
630
630
  // can use traits and extra fixture options here as you would with FactoryGuy#makeList
@@ -639,7 +639,7 @@ tests run as shown in the previous section (Using FactoryGuyTestMixin)**
639
639
  - pass in a record to handle reload
640
640
  - pass in fixture name and options ( including id if needed ) to handle making a record
641
641
  with those options and finding that record
642
- - handleFindOne ( deprecated alias )
642
+ - handleFindOne is a deprecated alias for handleFind
643
643
 
644
644
  *Passing in a model instance*
645
645
 
@@ -698,10 +698,16 @@ tests run as shown in the previous section (Using FactoryGuyTestMixin)**
698
698
 
699
699
 
700
700
  ##### handleCreate
701
- - options
701
+ - use chainable methods to build the response
702
+ - match - attributes that must be in request json
703
+ - andReturns - attributes to include in response json
704
+ - andFail - request should fail
705
+
706
+ - use hash of options to build the response
702
707
  - match - attributes that must be in request json
703
708
  - returns - attributes to include in response json
704
709
  - succeed - flag to indicate if the request should succeed ( default is true )
710
+ - this style will eventually be deprecated
705
711
 
706
712
  **Note**
707
713
 
@@ -732,17 +738,51 @@ In this case, you are are creating a 'project' record with a specific name, and
732
738
  to a particular user. To mock this createRecord call here are a few ways to do this using
733
739
  match and or returns options.
734
740
 
741
+
742
+ ######Using chainable methods
743
+
735
744
  ```javascript
736
745
  // Simplest case
737
746
  // Don't care about a match just handle createRecord for any project
738
747
  testHelper.handleCreate('project')
739
748
 
740
- // Exactly matching attributes
741
- testHelper.handleCreate('project', {match: {name: "Moo", user: user}})
749
+ // Matching some attributes
750
+ testHelper.handleCreate('project').match({match: {name: "Moo"})
751
+
752
+ // Match all attributes
753
+ testHelper.handleCreate('project').match({match: {name: "Moo", user: user})
754
+
755
+ // Exactly matching attributes, and returning extra attributes
756
+ testHelper.handleCreate('project')
757
+ .match({name: "Moo", user: user})
758
+ .andReturn({created_at: new Date()})
759
+
760
+ ```
761
+
762
+ *mocking a failed create*
763
+
764
+ ```javascript
765
+
766
+ // Mocking failure case is easy with chainable methods, just use #andFail
767
+ testHelper.handleCreate('project').match({match: {name: "Moo"}).andFail()
768
+
769
+ store.createRecord('project', {name: "Moo"}).save() //=> fails
770
+ ```
771
+
772
+
773
+ ######Using hash of options
774
+
775
+ ```javascript
776
+ // Simplest case
777
+ // Don't care about a match just handle createRecord for any project
778
+ testHelper.handleCreate('project')
742
779
 
743
780
  // Matching some attributes
744
781
  testHelper.handleCreate('project', {match: {name: "Moo"}})
745
782
 
783
+ // Match all attributes
784
+ testHelper.handleCreate('project', {match: {name: "Moo", user: user}})
785
+
746
786
  // Exactly matching attributes, and returning extra attributes
747
787
  testHelper.handleCreate('project', {
748
788
  match: {name: "Moo", user: user}, returns: {created_at: new Date()}
@@ -776,7 +816,7 @@ match and or returns options.
776
816
  *success case is the default*
777
817
 
778
818
  ```javascript
779
- var profile = testHelper.make('profile');
819
+ var profile = FactoryGuy.make('profile');
780
820
 
781
821
  // Pass in the model that will be updated ( if you have it available )
782
822
  testHelper.handleUpdate(profile);
@@ -792,7 +832,7 @@ match and or returns options.
792
832
  *mocking a failed update*
793
833
 
794
834
  ```javascript
795
- var profile = testHelper.make('profile');
835
+ var profile = FactoryGuy.make('profile');
796
836
 
797
837
  // set the succeed flag to 'false'
798
838
  testHelper.handleUpdate('profile', profile.id, false);
@@ -810,7 +850,7 @@ match and or returns options.
810
850
  *success case is the default*
811
851
 
812
852
  ```javascript
813
- var profile = testHelper.make('profile');
853
+ var profile = FactoryGuy.make('profile');
814
854
  testHelper.handleDelete('profile', profile.id);
815
855
 
816
856
  profile.destroyRecord() // => will succeed
@@ -819,7 +859,7 @@ match and or returns options.
819
859
  *mocking a failed delete*
820
860
 
821
861
  ```javascript
822
- var profile = testHelper.make('profile');
862
+ var profile = FactoryGuy.make('profile');
823
863
  // set the succeed flag to 'false'
824
864
  testHelper.handleDelete('profile', profile.id, false);
825
865
 
@@ -847,7 +887,7 @@ var viewHelper, user;
847
887
  module('User View', {
848
888
  setup: function() {
849
889
  viewHelper = ViewTestHelper.setup(App); // set up helper
850
- user = viewHelper.make('user'); // create a user in the store
890
+ user = FactoryGuy.make('user'); // create a user in the store
851
891
  visit('/users/'+user.id); // visit the users route
852
892
  },
853
893
  teardown: function() {
data/bower.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ember-data-factory-guy",
3
- "version": "0.9.5",
3
+ "version": "0.9.6",
4
4
  "authors": [
5
5
  "Daniel Sudol <dansudol@yahoo.com>",
6
6
  "Opak Alex <opak.alexandr@gmail.com>"
@@ -574,6 +574,80 @@ var FactoryGuy = {
574
574
  }
575
575
  };
576
576
 
577
+ var MockCreateRequest = function(url, store, modelName, options) {
578
+ var succeed = options.succeed === undefined ? true : options.succeed;
579
+ var matchArgs = options.match;
580
+ var returnArgs = options.returns;
581
+ var responseJson = {};
582
+ var expectedRequest = {};
583
+ var modelType = store.modelFor(modelName);
584
+
585
+ this.calculate = function() {
586
+ if (matchArgs) {
587
+ var record = store.createRecord(modelName, matchArgs);
588
+ expectedRequest = record.serialize();
589
+ }
590
+
591
+ if (succeed) {
592
+ var definition = FactoryGuy.modelDefinitions[modelName];
593
+ if (responseJson[modelName]) {
594
+ // already calculated once, keep the same id
595
+ responseJson[modelName] = $.extend({id: responseJson[modelName].id}, matchArgs, returnArgs);
596
+ } else {
597
+ responseJson[modelName] = $.extend({id: definition.nextId()}, matchArgs, returnArgs);
598
+ }
599
+ // Remove belongsTo associations since they will already be set when you called
600
+ // createRecord, so they don't need to be returned.
601
+ Ember.get(modelType, 'relationshipsByName').forEach(function (relationship) {
602
+ if (relationship.kind == 'belongsTo') {
603
+ delete responseJson[modelName][relationship.key];
604
+ }
605
+ })
606
+ }
607
+
608
+ }
609
+
610
+ this.match = function(matches) {
611
+ matchArgs = matches;
612
+ this.calculate();
613
+ return this;
614
+ }
615
+
616
+ this.andReturn = function(returns) {
617
+ returnArgs = returns;
618
+ this.calculate();
619
+ return this;
620
+ }
621
+
622
+ this.andFail = function() {
623
+ succeed = false;
624
+ return this;
625
+ }
626
+
627
+ this.handler = function(settings) {
628
+ if (settings.url != url || settings.type != 'POST') { return false}
629
+
630
+ if (matchArgs) {
631
+ var requestData = JSON.parse(settings.data)[modelName];
632
+ for (attribute in expectedRequest) {
633
+ if (expectedRequest[attribute] &&
634
+ requestData[attribute] != expectedRequest[attribute]) {
635
+ return false
636
+ }
637
+ }
638
+ }
639
+ var responseStatus = (succeed ? 200: 500);
640
+ return {
641
+ responseText: responseJson,
642
+ status: responseStatus
643
+ };
644
+ }
645
+
646
+ this.calculate();
647
+
648
+ $.mockjax(this.handler);
649
+ };
650
+
577
651
  (function () {
578
652
  DS.Store.reopen({
579
653
  /**
@@ -1086,53 +1160,10 @@ var FactoryGuyTestMixin = Em.Mixin.create({
1086
1160
  @param {Object} options hash of options for handling request
1087
1161
  */
1088
1162
  handleCreate: function (modelName, options) {
1089
- var opts = options === undefined ? {} : options;
1090
- var store = this.getStore()
1091
- var succeed = opts.succeed === undefined ? true : opts.succeed;
1092
- var match = opts.match || {};
1093
- var returnArgs = opts.returns || {};
1094
-
1095
- if (opts.match) {
1096
- var record = store.createRecord(modelName, match);
1097
- var expectedRequest = record.serialize();
1098
- }
1099
-
1100
- var modelType = store.modelFor(modelName)
1101
-
1102
- var responseJson = {};
1103
- if (succeed) {
1104
- var definition = FactoryGuy.modelDefinitions[modelName];
1105
- responseJson[modelName] = $.extend({id: definition.nextId()}, match, returnArgs);
1106
- // Remove belongsTo associations since they will already be set when you called
1107
- // createRecord, so they don't need to be returned.
1108
- Ember.get(modelType, 'relationshipsByName').forEach(function (relationship) {
1109
- if (relationship.kind == 'belongsTo') {
1110
- delete responseJson[modelName][relationship.key];
1111
- }
1112
- })
1113
- }
1114
-
1115
1163
  var url = this.buildURL(modelName);
1116
-
1117
- var handler = function(settings) {
1118
- if (settings.url != url || settings.type != 'POST') { return false}
1119
-
1120
- if (opts.match) {
1121
- var requestData = JSON.parse(settings.data)[modelName];
1122
- for (attribute in expectedRequest) {
1123
- if (expectedRequest[attribute] && requestData[attribute] != expectedRequest[attribute]) {
1124
- return false
1125
- }
1126
- }
1127
- }
1128
- var responseStatus = (succeed ? 200: 500);
1129
- return {
1130
- responseText: responseJson,
1131
- status: responseStatus
1132
- };
1133
- }
1134
-
1135
- $.mockjax(handler);
1164
+ var store = this.getStore();
1165
+ var opts = options === undefined ? {} : options;
1166
+ return new MockCreateRequest(url, store, modelName, opts);
1136
1167
  },
1137
1168
 
1138
1169
  /**
@@ -569,6 +569,80 @@ var FactoryGuy = {
569
569
  }
570
570
  };
571
571
 
572
+ var MockCreateRequest = function(url, store, modelName, options) {
573
+ var succeed = options.succeed === undefined ? true : options.succeed;
574
+ var matchArgs = options.match;
575
+ var returnArgs = options.returns;
576
+ var responseJson = {};
577
+ var expectedRequest = {};
578
+ var modelType = store.modelFor(modelName);
579
+
580
+ this.calculate = function() {
581
+ if (matchArgs) {
582
+ var record = store.createRecord(modelName, matchArgs);
583
+ expectedRequest = record.serialize();
584
+ }
585
+
586
+ if (succeed) {
587
+ var definition = FactoryGuy.modelDefinitions[modelName];
588
+ if (responseJson[modelName]) {
589
+ // already calculated once, keep the same id
590
+ responseJson[modelName] = $.extend({id: responseJson[modelName].id}, matchArgs, returnArgs);
591
+ } else {
592
+ responseJson[modelName] = $.extend({id: definition.nextId()}, matchArgs, returnArgs);
593
+ }
594
+ // Remove belongsTo associations since they will already be set when you called
595
+ // createRecord, so they don't need to be returned.
596
+ Ember.get(modelType, 'relationshipsByName').forEach(function (relationship) {
597
+ if (relationship.kind == 'belongsTo') {
598
+ delete responseJson[modelName][relationship.key];
599
+ }
600
+ })
601
+ }
602
+
603
+ }
604
+
605
+ this.match = function(matches) {
606
+ matchArgs = matches;
607
+ this.calculate();
608
+ return this;
609
+ }
610
+
611
+ this.andReturn = function(returns) {
612
+ returnArgs = returns;
613
+ this.calculate();
614
+ return this;
615
+ }
616
+
617
+ this.andFail = function() {
618
+ succeed = false;
619
+ return this;
620
+ }
621
+
622
+ this.handler = function(settings) {
623
+ if (settings.url != url || settings.type != 'POST') { return false}
624
+
625
+ if (matchArgs) {
626
+ var requestData = JSON.parse(settings.data)[modelName];
627
+ for (attribute in expectedRequest) {
628
+ if (expectedRequest[attribute] &&
629
+ requestData[attribute] != expectedRequest[attribute]) {
630
+ return false
631
+ }
632
+ }
633
+ }
634
+ var responseStatus = (succeed ? 200: 500);
635
+ return {
636
+ responseText: responseJson,
637
+ status: responseStatus
638
+ };
639
+ }
640
+
641
+ this.calculate();
642
+
643
+ $.mockjax(this.handler);
644
+ };
645
+
572
646
  (function () {
573
647
  DS.Store.reopen({
574
648
  /**
@@ -1081,53 +1155,10 @@ var FactoryGuyTestMixin = Em.Mixin.create({
1081
1155
  @param {Object} options hash of options for handling request
1082
1156
  */
1083
1157
  handleCreate: function (modelName, options) {
1084
- var opts = options === undefined ? {} : options;
1085
- var store = this.getStore()
1086
- var succeed = opts.succeed === undefined ? true : opts.succeed;
1087
- var match = opts.match || {};
1088
- var returnArgs = opts.returns || {};
1089
-
1090
- if (opts.match) {
1091
- var record = store.createRecord(modelName, match);
1092
- var expectedRequest = record.serialize();
1093
- }
1094
-
1095
- var modelType = store.modelFor(modelName)
1096
-
1097
- var responseJson = {};
1098
- if (succeed) {
1099
- var definition = FactoryGuy.modelDefinitions[modelName];
1100
- responseJson[modelName] = $.extend({id: definition.nextId()}, match, returnArgs);
1101
- // Remove belongsTo associations since they will already be set when you called
1102
- // createRecord, so they don't need to be returned.
1103
- Ember.get(modelType, 'relationshipsByName').forEach(function (relationship) {
1104
- if (relationship.kind == 'belongsTo') {
1105
- delete responseJson[modelName][relationship.key];
1106
- }
1107
- })
1108
- }
1109
-
1110
1158
  var url = this.buildURL(modelName);
1111
-
1112
- var handler = function(settings) {
1113
- if (settings.url != url || settings.type != 'POST') { return false}
1114
-
1115
- if (opts.match) {
1116
- var requestData = JSON.parse(settings.data)[modelName];
1117
- for (attribute in expectedRequest) {
1118
- if (expectedRequest[attribute] && requestData[attribute] != expectedRequest[attribute]) {
1119
- return false
1120
- }
1121
- }
1122
- }
1123
- var responseStatus = (succeed ? 200: 500);
1124
- return {
1125
- responseText: responseJson,
1126
- status: responseStatus
1127
- };
1128
- }
1129
-
1130
- $.mockjax(handler);
1159
+ var store = this.getStore();
1160
+ var opts = options === undefined ? {} : options;
1161
+ return new MockCreateRequest(url, store, modelName, opts);
1131
1162
  },
1132
1163
 
1133
1164
  /**
@@ -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);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)},handleFindAll: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)},handleFindMany:function(){Ember.deprecate("DEPRECATION Warning: use handleFindAll instead");this.handleFindAll.apply(this,arguments)},handleFind:function(){var args=Array.prototype.slice.call(arguments);Ember.assert("To handleFindOne pass in a model instance or a type and model options",args.length>0);var record,modelName;if(args[0]instanceof DS.Model){record=args[0];modelName=record.constructor.typeKey}else{record=FactoryGuy.make.apply(FactoryGuy,arguments);var name=arguments[0];modelName=FactoryGuy.lookupModelForFixtureName(name)}var responseJson={};var json=record.toJSON({includeId:true});responseJson[modelName.pluralize()]=json;var url=this.buildURL(modelName,record.id);this.stubEndpointForHttpRequest(url,responseJson)},handleFindOne:function(){this.handleFind.apply(this,arguments)},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 store=this.getStore();var succeed=opts.succeed===undefined?true:opts.succeed;var match=opts.match||{};var returnArgs=opts.returns||{};if(opts.match){var record=store.createRecord(modelName,match);var expectedRequest=record.serialize()}var modelType=store.modelFor(modelName);var responseJson={};if(succeed){var definition=FactoryGuy.modelDefinitions[modelName];responseJson[modelName]=$.extend({id:definition.nextId()},match,returnArgs);Ember.get(modelType,"relationshipsByName").forEach(function(relationship){if(relationship.kind=="belongsTo"){delete responseJson[modelName][relationship.key]}})}var url=this.buildURL(modelName);var handler=function(settings){if(settings.url!=url||settings.type!="POST"){return false}if(opts.match){var requestData=JSON.parse(settings.data)[modelName];for(attribute in expectedRequest){if(expectedRequest[attribute]&&requestData[attribute]!=expectedRequest[attribute]){return false}}}var responseStatus=succeed?200:500;return{responseText:responseJson,status:responseStatus}};$.mockjax(handler)},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={}}}};var MockCreateRequest=function(url,store,modelName,options){var succeed=options.succeed===undefined?true:options.succeed;var matchArgs=options.match;var returnArgs=options.returns;var responseJson={};var expectedRequest={};var modelType=store.modelFor(modelName);this.calculate=function(){if(matchArgs){var record=store.createRecord(modelName,matchArgs);expectedRequest=record.serialize()}if(succeed){var definition=FactoryGuy.modelDefinitions[modelName];if(responseJson[modelName]){responseJson[modelName]=$.extend({id:responseJson[modelName].id},matchArgs,returnArgs)}else{responseJson[modelName]=$.extend({id:definition.nextId()},matchArgs,returnArgs)}Ember.get(modelType,"relationshipsByName").forEach(function(relationship){if(relationship.kind=="belongsTo"){delete responseJson[modelName][relationship.key]}})}};this.match=function(matches){matchArgs=matches;this.calculate();return this};this.andReturn=function(returns){returnArgs=returns;this.calculate();return this};this.andFail=function(){succeed=false;return this};this.handler=function(settings){if(settings.url!=url||settings.type!="POST"){return false}if(matchArgs){var requestData=JSON.parse(settings.data)[modelName];for(attribute in expectedRequest){if(expectedRequest[attribute]&&requestData[attribute]!=expectedRequest[attribute]){return false}}}var responseStatus=succeed?200:500;return{responseText:responseJson,status:responseStatus}};this.calculate();$.mockjax(this.handler)};(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)},handleFindAll: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)},handleFindMany:function(){Ember.deprecate("DEPRECATION Warning: use handleFindAll instead");this.handleFindAll.apply(this,arguments)},handleFind:function(){var args=Array.prototype.slice.call(arguments);Ember.assert("To handleFindOne pass in a model instance or a type and model options",args.length>0);var record,modelName;if(args[0]instanceof DS.Model){record=args[0];modelName=record.constructor.typeKey}else{record=FactoryGuy.make.apply(FactoryGuy,arguments);var name=arguments[0];modelName=FactoryGuy.lookupModelForFixtureName(name)}var responseJson={};var json=record.toJSON({includeId:true});responseJson[modelName.pluralize()]=json;var url=this.buildURL(modelName,record.id);this.stubEndpointForHttpRequest(url,responseJson)},handleFindOne:function(){this.handleFind.apply(this,arguments)},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 url=this.buildURL(modelName);var store=this.getStore();var opts=options===undefined?{}:options;return new MockCreateRequest(url,store,modelName,opts)},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}
data/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ember-data-factory-guy",
3
- "version": "0.9.5",
3
+ "version": "0.9.6",
4
4
  "authors": [
5
5
  "Daniel Sudol <dansudol@yahoo.com>",
6
6
  "Opak Alex <opak.alexandr@gmail.com>"
@@ -233,53 +233,10 @@ var FactoryGuyTestMixin = Em.Mixin.create({
233
233
  @param {Object} options hash of options for handling request
234
234
  */
235
235
  handleCreate: function (modelName, options) {
236
- var opts = options === undefined ? {} : options;
237
- var store = this.getStore()
238
- var succeed = opts.succeed === undefined ? true : opts.succeed;
239
- var match = opts.match || {};
240
- var returnArgs = opts.returns || {};
241
-
242
- if (opts.match) {
243
- var record = store.createRecord(modelName, match);
244
- var expectedRequest = record.serialize();
245
- }
246
-
247
- var modelType = store.modelFor(modelName)
248
-
249
- var responseJson = {};
250
- if (succeed) {
251
- var definition = FactoryGuy.modelDefinitions[modelName];
252
- responseJson[modelName] = $.extend({id: definition.nextId()}, match, returnArgs);
253
- // Remove belongsTo associations since they will already be set when you called
254
- // createRecord, so they don't need to be returned.
255
- Ember.get(modelType, 'relationshipsByName').forEach(function (relationship) {
256
- if (relationship.kind == 'belongsTo') {
257
- delete responseJson[modelName][relationship.key];
258
- }
259
- })
260
- }
261
-
262
236
  var url = this.buildURL(modelName);
263
-
264
- var handler = function(settings) {
265
- if (settings.url != url || settings.type != 'POST') { return false}
266
-
267
- if (opts.match) {
268
- var requestData = JSON.parse(settings.data)[modelName];
269
- for (attribute in expectedRequest) {
270
- if (expectedRequest[attribute] && requestData[attribute] != expectedRequest[attribute]) {
271
- return false
272
- }
273
- }
274
- }
275
- var responseStatus = (succeed ? 200: 500);
276
- return {
277
- responseText: responseJson,
278
- status: responseStatus
279
- };
280
- }
281
-
282
- $.mockjax(handler);
237
+ var store = this.getStore();
238
+ var opts = options === undefined ? {} : options;
239
+ return new MockCreateRequest(url, store, modelName, opts);
283
240
  },
284
241
 
285
242
  /**
@@ -0,0 +1,73 @@
1
+ var MockCreateRequest = function(url, store, modelName, options) {
2
+ var succeed = options.succeed === undefined ? true : options.succeed;
3
+ var matchArgs = options.match;
4
+ var returnArgs = options.returns;
5
+ var responseJson = {};
6
+ var expectedRequest = {};
7
+ var modelType = store.modelFor(modelName);
8
+
9
+ this.calculate = function() {
10
+ if (matchArgs) {
11
+ var record = store.createRecord(modelName, matchArgs);
12
+ expectedRequest = record.serialize();
13
+ }
14
+
15
+ if (succeed) {
16
+ var definition = FactoryGuy.modelDefinitions[modelName];
17
+ if (responseJson[modelName]) {
18
+ // already calculated once, keep the same id
19
+ responseJson[modelName] = $.extend({id: responseJson[modelName].id}, matchArgs, returnArgs);
20
+ } else {
21
+ responseJson[modelName] = $.extend({id: definition.nextId()}, matchArgs, returnArgs);
22
+ }
23
+ // Remove belongsTo associations since they will already be set when you called
24
+ // createRecord, so they don't need to be returned.
25
+ Ember.get(modelType, 'relationshipsByName').forEach(function (relationship) {
26
+ if (relationship.kind == 'belongsTo') {
27
+ delete responseJson[modelName][relationship.key];
28
+ }
29
+ })
30
+ }
31
+
32
+ }
33
+
34
+ this.match = function(matches) {
35
+ matchArgs = matches;
36
+ this.calculate();
37
+ return this;
38
+ }
39
+
40
+ this.andReturn = function(returns) {
41
+ returnArgs = returns;
42
+ this.calculate();
43
+ return this;
44
+ }
45
+
46
+ this.andFail = function() {
47
+ succeed = false;
48
+ return this;
49
+ }
50
+
51
+ this.handler = function(settings) {
52
+ if (settings.url != url || settings.type != 'POST') { return false}
53
+
54
+ if (matchArgs) {
55
+ var requestData = JSON.parse(settings.data)[modelName];
56
+ for (attribute in expectedRequest) {
57
+ if (expectedRequest[attribute] &&
58
+ requestData[attribute] != expectedRequest[attribute]) {
59
+ return false
60
+ }
61
+ }
62
+ }
63
+ var responseStatus = (succeed ? 200: 500);
64
+ return {
65
+ responseText: responseJson,
66
+ status: responseStatus
67
+ };
68
+ }
69
+
70
+ this.calculate();
71
+
72
+ $.mockjax(this.handler);
73
+ };
@@ -28,7 +28,7 @@ module('FactoryGuyTestMixin (using mockjax) with DS.RESTAdapter', {
28
28
  setup: function () {
29
29
  testHelper = TestHelper.setup(DS.RESTAdapter);
30
30
  store = testHelper.getStore();
31
- make = function() {return testHelper.make.apply(testHelper,arguments)}
31
+ make = function() {return FactoryGuy.make.apply(FactoryGuy,arguments)}
32
32
  },
33
33
  teardown: function () {
34
34
  testHelper.teardown();
@@ -233,7 +233,7 @@ module('FactoryGuyTestMixin (using mockjax) with DS.ActiveModelAdapter', {
233
233
  setup: function () {
234
234
  testHelper = TestHelper.setup(DS.ActiveModelAdapter);
235
235
  store = testHelper.getStore();
236
- make = function() {return testHelper.make.apply(testHelper,arguments)}
236
+ make = function() {return FactoryGuy.make.apply(FactoryGuy,arguments)}
237
237
  },
238
238
  teardown: function () {
239
239
  testHelper.teardown();
@@ -241,8 +241,9 @@ module('FactoryGuyTestMixin (using mockjax) with DS.ActiveModelAdapter', {
241
241
  });
242
242
 
243
243
 
244
- /////// handleCreate //////////
244
+ /////// handleCreate //////////
245
245
 
246
+ /////// with hash of parameters ///////////////////
246
247
  asyncTest("#handleCreate with no specific match", function() {
247
248
  testHelper.handleCreate('profile');
248
249
 
@@ -394,6 +395,128 @@ asyncTest("#handleCreate match but still fail", function() {
394
395
  )
395
396
  });
396
397
 
398
+ /////// handleCreate //////////
399
+ /////// with chaining methods ///////////////////
400
+
401
+ asyncTest("#handleCreate match some attributes with match method", function() {
402
+ var customDescription = "special description"
403
+ var date = new Date();
404
+
405
+ testHelper.handleCreate('profile').match({description: customDescription});
406
+
407
+ store.createRecord('profile', {
408
+ description: customDescription, created_at: date
409
+ }).save().then(function(profile) {
410
+ ok(profile instanceof Profile)
411
+ ok(profile.id == 1)
412
+ ok(profile.get('description') == customDescription)
413
+ start();
414
+ });
415
+ });
416
+
417
+ asyncTest("#handleCreate match all attributes with match method", function() {
418
+ var customDescription = "special description"
419
+ var date = new Date();
420
+
421
+ testHelper.handleCreate('profile').match({description: customDescription, created_at: date});
422
+
423
+ store.createRecord('profile', {
424
+ description: customDescription, created_at: date
425
+ }).save().then(function(profile) {
426
+ ok(profile instanceof Profile)
427
+ ok(profile.id == 1)
428
+ ok(profile.get('description') == customDescription)
429
+ ok(profile.get('created_at') == date.toString())
430
+ start();
431
+ });
432
+ });
433
+
434
+ asyncTest("#handleCreate match belongsTo association with match method", function() {
435
+ var company = make('company')
436
+ testHelper.handleCreate('profile').match({company: company})
437
+
438
+ store.createRecord('profile', {company: company}).save().then(function(profile) {
439
+ ok(profile.get('company') == company)
440
+ start();
441
+ });
442
+ });
443
+
444
+ asyncTest("#handleCreate match belongsTo polymorphic association with match method", function() {
445
+ var group = make('group')
446
+ testHelper.handleCreate('profile').match({group: group})
447
+
448
+ store.createRecord('profile', {group: group}).save().then(function(profile) {
449
+ ok(profile.get('group') == group)
450
+ start();
451
+ });
452
+ });
453
+
454
+
455
+
456
+ asyncTest("#handleCreate returns attributes with andReturns method", function() {
457
+ var date = new Date()
458
+
459
+ testHelper.handleCreate('profile').andReturn({created_at: date});
460
+
461
+ store.createRecord('profile').save().then(function(profile) {
462
+ ok(profile.get('created_at') == date.toString())
463
+ start();
464
+ });
465
+ });
466
+
467
+ asyncTest("#handleCreate match attributes and return attributes with match and andReturn methods", function() {
468
+ var date = new Date()
469
+ var customDescription = "special description"
470
+ var company = make('company')
471
+ var group = make('big_group')
472
+
473
+ testHelper.handleCreate('profile')
474
+ .match({description: customDescription, company: company, group: group})
475
+ .andReturn({created_at: new Date()})
476
+
477
+ store.createRecord('profile', {
478
+ description: customDescription, company: company, group: group
479
+ }).save().then(function(profile) {
480
+ start();
481
+ ok(profile.get('created_at') == date.toString())
482
+ ok(profile.get('group') == group)
483
+ ok(profile.get('company') == company)
484
+ ok(profile.get('description') == customDescription)
485
+ });
486
+ });
487
+
488
+
489
+ asyncTest("#handleCreate failure with andFail method", function() {
490
+ testHelper.handleCreate('profile').andFail();
491
+
492
+ store.createRecord('profile').save()
493
+ .then(
494
+ function() {},
495
+ function() {
496
+ ok(true)
497
+ start();
498
+ }
499
+ )
500
+ });
501
+
502
+
503
+ asyncTest("#handleCreate match but still fail with chaining methods", function() {
504
+ var description = "special description"
505
+
506
+ testHelper.handleCreate('profile').match({description: description}).andFail();
507
+
508
+ store.createRecord('profile', {description: description}).save()
509
+ .then(
510
+ function() {},
511
+ function() {
512
+ ok(true)
513
+ start();
514
+ }
515
+ )
516
+ });
517
+
518
+
519
+
397
520
 
398
521
 
399
522
  /////// handleFindAll //////////
@@ -534,6 +657,4 @@ asyncTest("#handleDelete failure case", function() {
534
657
  start();
535
658
  }
536
659
  );
537
- });
538
-
539
-
660
+ });
@@ -1081,53 +1081,10 @@ var FactoryGuyTestMixin = Em.Mixin.create({
1081
1081
  @param {Object} options hash of options for handling request
1082
1082
  */
1083
1083
  handleCreate: function (modelName, options) {
1084
- var opts = options === undefined ? {} : options;
1085
- var store = this.getStore()
1086
- var succeed = opts.succeed === undefined ? true : opts.succeed;
1087
- var match = opts.match || {};
1088
- var returnArgs = opts.returns || {};
1089
-
1090
- if (opts.match) {
1091
- var record = store.createRecord(modelName, match);
1092
- var expectedRequest = record.serialize();
1093
- }
1094
-
1095
- var modelType = store.modelFor(modelName)
1096
-
1097
- var responseJson = {};
1098
- if (succeed) {
1099
- var definition = FactoryGuy.modelDefinitions[modelName];
1100
- responseJson[modelName] = $.extend({id: definition.nextId()}, match, returnArgs);
1101
- // Remove belongsTo associations since they will already be set when you called
1102
- // createRecord, so they don't need to be returned.
1103
- Ember.get(modelType, 'relationshipsByName').forEach(function (relationship) {
1104
- if (relationship.kind == 'belongsTo') {
1105
- delete responseJson[modelName][relationship.key];
1106
- }
1107
- })
1108
- }
1109
-
1110
1084
  var url = this.buildURL(modelName);
1111
-
1112
- var handler = function(settings) {
1113
- if (settings.url != url || settings.type != 'POST') { return false}
1114
-
1115
- if (opts.match) {
1116
- var requestData = JSON.parse(settings.data)[modelName];
1117
- for (attribute in expectedRequest) {
1118
- if (expectedRequest[attribute] && requestData[attribute] != expectedRequest[attribute]) {
1119
- return false
1120
- }
1121
- }
1122
- }
1123
- var responseStatus = (succeed ? 200: 500);
1124
- return {
1125
- responseText: responseJson,
1126
- status: responseStatus
1127
- };
1128
- }
1129
-
1130
- $.mockjax(handler);
1085
+ var store = this.getStore();
1086
+ var opts = options === undefined ? {} : options;
1087
+ return new MockCreateRequest(url, store, modelName, opts);
1131
1088
  },
1132
1089
 
1133
1090
  /**
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ember-data-factory-guy
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.9.5
4
+ version: 0.9.6
5
5
  platform: ruby
6
6
  authors:
7
7
  - Daniel Sudol
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2015-01-17 00:00:00.000000000 Z
12
+ date: 2015-01-19 00:00:00.000000000 Z
13
13
  dependencies: []
14
14
  description: Easily create Fixtures for Ember Data
15
15
  email:
@@ -36,6 +36,7 @@ files:
36
36
  - src/factory_guy.js
37
37
  - src/factory_guy_test_mixin.js
38
38
  - src/has_many.js
39
+ - src/mock_create_request.js
39
40
  - src/model_definition.js
40
41
  - src/prologue.js
41
42
  - src/sequence.js