aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/autosave_association_test.rb
blob: ae5127cc567b3da9d3e324e0bb24bc3d941ccd00 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
require "cases/helper"
require "models/bird"
require "models/comment"
require "models/company"
require "models/customer"
require "models/developer"
require "models/computer"
require "models/invoice"
require "models/line_item"
require "models/order"
require "models/parrot"
require "models/person"
require "models/pirate"
require "models/post"
require "models/reader"
require "models/ship"
require "models/ship_part"
require "models/tag"
require "models/tagging"
require "models/treasure"
require "models/eye"
require "models/electron"
require "models/molecule"
require "models/member"
require "models/member_detail"
require "models/organization"
require "models/guitar"
require "models/tuning_peg"

class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
  def test_autosave_validation
    person = Class.new(ActiveRecord::Base) {
      self.table_name = "people"
      validate :should_be_cool, on: :create
      def self.name; "Person"; end

      private

      def should_be_cool
        unless self.first_name == "cool"
          errors.add :first_name, "not cool"
        end
      end
    }
    reference = Class.new(ActiveRecord::Base) {
      self.table_name = "references"
      def self.name; "Reference"; end
      belongs_to :person, autosave: true, anonymous_class: person
    }

    u = person.create!(first_name: "cool")
    u.update_attributes!(first_name: "nah") # still valid because validation only applies on 'create'
    assert reference.create!(person: u).persisted?
  end

  def test_should_not_add_the_same_callbacks_multiple_times_for_has_one
    assert_no_difference_when_adding_callbacks_twice_for Pirate, :ship
  end

  def test_should_not_add_the_same_callbacks_multiple_times_for_belongs_to
    assert_no_difference_when_adding_callbacks_twice_for Ship, :pirate
  end

  def test_should_not_add_the_same_callbacks_multiple_times_for_has_many
    assert_no_difference_when_adding_callbacks_twice_for Pirate, :birds
  end

  def test_should_not_add_the_same_callbacks_multiple_times_for_has_and_belongs_to_many
    assert_no_difference_when_adding_callbacks_twice_for Pirate, :parrots
  end

  def test_cyclic_autosaves_do_not_add_multiple_validations
    ship = ShipWithoutNestedAttributes.new
    ship.prisoners.build

    assert_not ship.valid?
    assert_equal 1, ship.errors[:name].length
  end

  private

    def assert_no_difference_when_adding_callbacks_twice_for(model, association_name)
      reflection = model.reflect_on_association(association_name)
      assert_no_difference "callbacks_for_model(#{model.name}).length" do
        model.send(:add_autosave_association_callbacks, reflection)
      end
    end

    def callbacks_for_model(model)
      model.instance_variables.grep(/_callbacks$/).flat_map do |ivar|
        model.instance_variable_get(ivar)
      end
    end
end

class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
  fixtures :companies, :accounts

  def test_should_save_parent_but_not_invalid_child
    firm = Firm.new(name: "GlobalMegaCorp")
    assert firm.valid?

    firm.build_account_using_primary_key
    assert !firm.build_account_using_primary_key.valid?

    assert firm.save
    assert !firm.account_using_primary_key.persisted?
  end

  def test_save_fails_for_invalid_has_one
    firm = Firm.first
    assert firm.valid?

    firm.build_account

    assert !firm.account.valid?
    assert !firm.valid?
    assert !firm.save
    assert_equal ["is invalid"], firm.errors["account"]
  end

  def test_save_succeeds_for_invalid_has_one_with_validate_false
    firm = Firm.first
    assert firm.valid?

    firm.build_unvalidated_account

    assert !firm.unvalidated_account.valid?
    assert firm.valid?
    assert firm.save
  end

  def test_build_before_child_saved
    firm = Firm.find(1)

    account = firm.build_account("credit_limit" => 1000)
    assert_equal account, firm.account
    assert !account.persisted?
    assert firm.save
    assert_equal account, firm.account
    assert account.persisted?
  end

  def test_build_before_either_saved
    firm = Firm.new("name" => "GlobalMegaCorp")

    firm.account = account = Account.new("credit_limit" => 1000)
    assert_equal account, firm.account
    assert !account.persisted?
    assert firm.save
    assert_equal account, firm.account
    assert account.persisted?
  end

  def test_assignment_before_parent_saved
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.account = a = Account.find(1)
    assert !firm.persisted?
    assert_equal a, firm.account
    assert firm.save
    assert_equal a, firm.account
    firm.association(:account).reload
    assert_equal a, firm.account
  end

  def test_assignment_before_either_saved
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.account = a = Account.new("credit_limit" => 1000)
    assert !firm.persisted?
    assert !a.persisted?
    assert_equal a, firm.account
    assert firm.save
    assert firm.persisted?
    assert a.persisted?
    assert_equal a, firm.account
    firm.association(:account).reload
    assert_equal a, firm.account
  end

  def test_not_resaved_when_unchanged
    firm = Firm.all.merge!(includes: :account).first
    firm.name += "-changed"
    assert_queries(1) { firm.save! }

    firm = Firm.first
    firm.account = Account.first
    assert_queries(Firm.partial_writes? ? 0 : 1) { firm.save! }

    firm = Firm.first.dup
    firm.account = Account.first
    assert_queries(2) { firm.save! }

    firm = Firm.first.dup
    firm.account = Account.first.dup
    assert_queries(2) { firm.save! }
  end

  def test_callbacks_firing_order_on_create
    eye = Eye.create(iris_attributes: {color: "honey"})
    assert_equal [true, false], eye.after_create_callbacks_stack
  end

  def test_callbacks_firing_order_on_update
    eye = Eye.create(iris_attributes: {color: "honey"})
    eye.update(iris_attributes: {color: "green"})
    assert_equal [true, false], eye.after_update_callbacks_stack
  end

  def test_callbacks_firing_order_on_save
    eye = Eye.create(iris_attributes: {color: "honey"})
    assert_equal [false, false], eye.after_save_callbacks_stack

    eye.update(iris_attributes: {color: "blue"})
    assert_equal [false, false, false, false], eye.after_save_callbacks_stack
  end
end

class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
  fixtures :companies, :posts, :tags, :taggings

  def test_should_save_parent_but_not_invalid_child
    client = Client.new(name: "Joe (the Plumber)")
    assert client.valid?

    client.build_firm
    assert !client.firm.valid?

    assert client.save
    assert !client.firm.persisted?
  end

  def test_save_fails_for_invalid_belongs_to
    # Oracle saves empty string as NULL therefore :message changed to one space
    assert log = AuditLog.create(developer_id: 0, message: " ")

    log.developer = Developer.new
    assert !log.developer.valid?
    assert !log.valid?
    assert !log.save
    assert_equal ["is invalid"], log.errors["developer"]
  end

  def test_save_succeeds_for_invalid_belongs_to_with_validate_false
    # Oracle saves empty string as NULL therefore :message changed to one space
    assert log = AuditLog.create(developer_id: 0, message: " ")

    log.unvalidated_developer = Developer.new
    assert !log.unvalidated_developer.valid?
    assert log.valid?
    assert log.save
  end

  def test_assignment_before_parent_saved
    client = Client.first
    apple = Firm.new("name" => "Apple")
    client.firm = apple
    assert_equal apple, client.firm
    assert !apple.persisted?
    assert client.save
    assert apple.save
    assert apple.persisted?
    assert_equal apple, client.firm
    client.association(:firm).reload
    assert_equal apple, client.firm
  end

  def test_assignment_before_either_saved
    final_cut = Client.new("name" => "Final Cut")
    apple = Firm.new("name" => "Apple")
    final_cut.firm = apple
    assert !final_cut.persisted?
    assert !apple.persisted?
    assert final_cut.save
    assert final_cut.persisted?
    assert apple.persisted?
    assert_equal apple, final_cut.firm
    final_cut.association(:firm).reload
    assert_equal apple, final_cut.firm
  end

  def test_store_two_association_with_one_save
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.new

    customer1 = order.billing = Customer.new
    customer2 = order.shipping = Customer.new
    assert order.save
    assert_equal customer1, order.billing
    assert_equal customer2, order.shipping

    order.reload

    assert_equal customer1, order.billing
    assert_equal customer2, order.shipping

    assert_equal num_orders + 1, Order.count
    assert_equal num_customers + 2, Customer.count
  end

  def test_store_association_in_two_relations_with_one_save
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.new

    customer = order.billing = order.shipping = Customer.new
    assert order.save
    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    order.reload

    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    assert_equal num_orders + 1, Order.count
    assert_equal num_customers + 1, Customer.count
  end

  def test_store_association_in_two_relations_with_one_save_in_existing_object
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.create

    customer = order.billing = order.shipping = Customer.new
    assert order.save
    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    order.reload

    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    assert_equal num_orders + 1, Order.count
    assert_equal num_customers + 1, Customer.count
  end

  def test_store_association_in_two_relations_with_one_save_in_existing_object_with_values
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.create

    customer = order.billing = order.shipping = Customer.new
    assert order.save
    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    order.reload

    customer = order.billing = order.shipping = Customer.new

    assert order.save
    order.reload

    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    assert_equal num_orders + 1, Order.count
    assert_equal num_customers + 2, Customer.count
  end

  def test_store_association_with_a_polymorphic_relationship
    num_tagging = Tagging.count
    tags(:misc).create_tagging(taggable: posts(:thinking))
    assert_equal num_tagging + 1, Tagging.count
  end

  def test_build_and_then_save_parent_should_not_reload_target
    client = Client.first
    apple = client.build_firm(name: "Apple")
    client.save!
    assert_no_queries { assert_equal apple, client.firm }
  end

  def test_validation_does_not_validate_stale_association_target
    valid_developer   = Developer.create!(name: "Dude", salary: 50_000)
    invalid_developer = Developer.new()

    auditlog = AuditLog.new(message: "foo")
    auditlog.developer    = invalid_developer
    auditlog.developer_id = valid_developer.id

    assert auditlog.valid?
  end
end

class TestDefaultAutosaveAssociationOnAHasManyAssociationWithAcceptsNestedAttributes < ActiveRecord::TestCase
  def test_invalid_adding_with_nested_attributes
    molecule = Molecule.new
    valid_electron = Electron.new(name: "electron")
    invalid_electron = Electron.new

    molecule.electrons = [valid_electron, invalid_electron]
    molecule.save

    assert_not invalid_electron.valid?
    assert valid_electron.valid?
    assert_not molecule.persisted?, "Molecule should not be persisted when its electrons are invalid"
  end

  def test_errors_should_be_indexed_when_passed_as_array
    guitar = Guitar.new
    tuning_peg_valid = TuningPeg.new
    tuning_peg_valid.pitch = 440.0
    tuning_peg_invalid = TuningPeg.new

    guitar.tuning_pegs = [tuning_peg_valid, tuning_peg_invalid]

    assert_not tuning_peg_invalid.valid?
    assert tuning_peg_valid.valid?
    assert_not guitar.valid?
    assert_equal ["is not a number"], guitar.errors["tuning_pegs[1].pitch"]
    assert_not_equal ["is not a number"], guitar.errors["tuning_pegs.pitch"]
  end

  def test_errors_should_be_indexed_when_global_flag_is_set
    old_attribute_config = ActiveRecord::Base.index_nested_attribute_errors
    ActiveRecord::Base.index_nested_attribute_errors = true

    molecule = Molecule.new
    valid_electron = Electron.new(name: "electron")
    invalid_electron = Electron.new

    molecule.electrons = [valid_electron, invalid_electron]

    assert_not invalid_electron.valid?
    assert valid_electron.valid?
    assert_not molecule.valid?
    assert_equal ["can't be blank"], molecule.errors["electrons[1].name"]
    assert_not_equal ["can't be blank"], molecule.errors["electrons.name"]
  ensure
    ActiveRecord::Base.index_nested_attribute_errors = old_attribute_config
  end

  def test_errors_details_should_be_set
    molecule = Molecule.new
    valid_electron = Electron.new(name: "electron")
    invalid_electron = Electron.new

    molecule.electrons = [valid_electron, invalid_electron]

    assert_not invalid_electron.valid?
    assert valid_electron.valid?
    assert_not molecule.valid?
    assert_equal [{error: :blank}], molecule.errors.details["electrons.name"]
  end

  def test_errors_details_should_be_indexed_when_passed_as_array
    guitar = Guitar.new
    tuning_peg_valid = TuningPeg.new
    tuning_peg_valid.pitch = 440.0
    tuning_peg_invalid = TuningPeg.new

    guitar.tuning_pegs = [tuning_peg_valid, tuning_peg_invalid]

    assert_not tuning_peg_invalid.valid?
    assert tuning_peg_valid.valid?
    assert_not guitar.valid?
    assert_equal [{error: :not_a_number, value: nil}] , guitar.errors.details["tuning_pegs[1].pitch"]
    assert_equal [], guitar.errors.details["tuning_pegs.pitch"]
  end

  def test_errors_details_should_be_indexed_when_global_flag_is_set
    old_attribute_config = ActiveRecord::Base.index_nested_attribute_errors
    ActiveRecord::Base.index_nested_attribute_errors = true

    molecule = Molecule.new
    valid_electron = Electron.new(name: "electron")
    invalid_electron = Electron.new

    molecule.electrons = [valid_electron, invalid_electron]

    assert_not invalid_electron.valid?
    assert valid_electron.valid?
    assert_not molecule.valid?
    assert_equal [{error: :blank}], molecule.errors.details["electrons[1].name"]
    assert_equal [], molecule.errors.details["electrons.name"]
  ensure
    ActiveRecord::Base.index_nested_attribute_errors = old_attribute_config
  end

  def test_valid_adding_with_nested_attributes
    molecule = Molecule.new
    valid_electron = Electron.new(name: "electron")

    molecule.electrons = [valid_electron]
    molecule.save

    assert valid_electron.valid?
    assert molecule.persisted?
    assert_equal 1, molecule.electrons.count
  end
end

class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
  fixtures :companies, :people

  def test_invalid_adding
    firm = Firm.find(1)
    assert !(firm.clients_of_firm << c = Client.new)
    assert !c.persisted?
    assert !firm.valid?
    assert !firm.save
    assert !c.persisted?
  end

  def test_invalid_adding_before_save
    new_firm = Firm.new("name" => "A New Firm, Inc")
    new_firm.clients_of_firm.concat([c = Client.new, Client.new("name" => "Apple")])
    assert !c.persisted?
    assert !c.valid?
    assert !new_firm.valid?
    assert !new_firm.save
    assert !c.persisted?
    assert !new_firm.persisted?
  end

  def test_invalid_adding_with_validate_false
    firm = Firm.first
    client = Client.new
    firm.unvalidated_clients_of_firm << client

    assert firm.valid?
    assert !client.valid?
    assert firm.save
    assert !client.persisted?
  end

  def test_valid_adding_with_validate_false
    no_of_clients = Client.count

    firm = Firm.first
    client = Client.new("name" => "Apple")

    assert firm.valid?
    assert client.valid?
    assert !client.persisted?

    firm.unvalidated_clients_of_firm << client

    assert firm.save
    assert client.persisted?
    assert_equal no_of_clients + 1, Client.count
  end

  def test_invalid_build
    new_client = companies(:first_firm).clients_of_firm.build
    assert !new_client.persisted?
    assert !new_client.valid?
    assert_equal new_client, companies(:first_firm).clients_of_firm.last
    assert !companies(:first_firm).save
    assert !new_client.persisted?
    assert_equal 2, companies(:first_firm).clients_of_firm.reload.size
  end

  def test_adding_before_save
    no_of_firms = Firm.count
    no_of_clients = Client.count

    new_firm = Firm.new("name" => "A New Firm, Inc")
    c = Client.new("name" => "Apple")

    new_firm.clients_of_firm.push Client.new("name" => "Natural Company")
    assert_equal 1, new_firm.clients_of_firm.size
    new_firm.clients_of_firm << c
    assert_equal 2, new_firm.clients_of_firm.size

    assert_equal no_of_firms, Firm.count      # Firm was not saved to database.
    assert_equal no_of_clients, Client.count  # Clients were not saved to database.
    assert new_firm.save
    assert new_firm.persisted?
    assert c.persisted?
    assert_equal new_firm, c.firm
    assert_equal no_of_firms + 1, Firm.count      # Firm was saved to database.
    assert_equal no_of_clients + 2, Client.count  # Clients were saved to database.

    assert_equal 2, new_firm.clients_of_firm.size
    assert_equal 2, new_firm.clients_of_firm.reload.size
  end

  def test_assign_ids
    firm = Firm.new("name" => "Apple")
    firm.client_ids = [companies(:first_client).id, companies(:second_client).id]
    firm.save
    firm.reload
    assert_equal 2, firm.clients.length
    assert firm.clients.include?(companies(:second_client))
  end

  def test_assign_ids_for_through_a_belongs_to
    post = Post.new(title: "Assigning IDs works!", body: "You heard it here first, folks!")
    post.person_ids = [people(:david).id, people(:michael).id]
    post.save
    post.reload
    assert_equal 2, post.people.length
    assert post.people.include?(people(:david))
  end

  def test_build_before_save
    company = companies(:first_firm)
    new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build("name" => "Another Client") }
    assert !company.clients_of_firm.loaded?

    company.name += "-changed"
    assert_queries(2) { assert company.save }
    assert new_client.persisted?
    assert_equal 3, company.clients_of_firm.reload.size
  end

  def test_build_many_before_save
    company = companies(:first_firm)
    assert_no_queries(ignore_none: false) { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }

    company.name += "-changed"
    assert_queries(3) { assert company.save }
    assert_equal 4, company.clients_of_firm.reload.size
  end

  def test_build_via_block_before_save
    company = companies(:first_firm)
    new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build {|client| client.name = "Another Client" } }
    assert !company.clients_of_firm.loaded?

    company.name += "-changed"
    assert_queries(2) { assert company.save }
    assert new_client.persisted?
    assert_equal 3, company.clients_of_firm.reload.size
  end

  def test_build_many_via_block_before_save
    company = companies(:first_firm)
    assert_no_queries(ignore_none: false) do
      company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) do |client|
        client.name = "changed"
      end
    end

    company.name += "-changed"
    assert_queries(3) { assert company.save }
    assert_equal 4, company.clients_of_firm.reload.size
  end

  def test_replace_on_new_object
    firm = Firm.new("name" => "New Firm")
    firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
    assert firm.save
    firm.reload
    assert_equal 2, firm.clients.length
    assert firm.clients.include?(Client.find_by_name("New Client"))
  end
end

class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase
  def test_autosave_new_record_on_belongs_to_can_be_disabled_per_relationship
    new_account = Account.new("credit_limit" => 1000)
    new_firm = Firm.new("name" => "some firm")

    assert !new_firm.persisted?
    new_account.firm = new_firm
    new_account.save!

    assert new_firm.persisted?

    new_account = Account.new("credit_limit" => 1000)
    new_autosaved_firm = Firm.new("name" => "some firm")

    assert !new_autosaved_firm.persisted?
    new_account.unautosaved_firm = new_autosaved_firm
    new_account.save!

    assert !new_autosaved_firm.persisted?
  end

  def test_autosave_new_record_on_has_one_can_be_disabled_per_relationship
    firm = Firm.new("name" => "some firm")
    account = Account.new("credit_limit" => 1000)

    assert !account.persisted?
    firm.account = account
    firm.save!

    assert account.persisted?

    firm = Firm.new("name" => "some firm")
    account = Account.new("credit_limit" => 1000)

    firm.unautosaved_account = account

    assert !account.persisted?
    firm.unautosaved_account = account
    firm.save!

    assert !account.persisted?
  end

  def test_autosave_new_record_on_has_many_can_be_disabled_per_relationship
    firm = Firm.new("name" => "some firm")
    account = Account.new("credit_limit" => 1000)

    assert !account.persisted?
    firm.accounts << account

    firm.save!
    assert account.persisted?

    firm = Firm.new("name" => "some firm")
    account = Account.new("credit_limit" => 1000)

    assert !account.persisted?
    firm.unautosaved_accounts << account

    firm.save!
    assert !account.persisted?
  end

  def test_autosave_new_record_with_after_create_callback
    post = PostWithAfterCreateCallback.new(title: "Captain Murphy", body: "is back")
    post.comments.build(body: "foo")
    post.save!

    assert_not_nil post.author_id
  end
end

class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
  self.use_transactional_tests = false

  setup do
    @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
    @ship = @pirate.create_ship(name: "Nights Dirty Lightning")
  end

  teardown do
    # We are running without transactional tests and need to cleanup.
    Bird.delete_all
    Parrot.delete_all
    @ship.delete
    @pirate.delete
  end

  # reload
  def test_a_marked_for_destruction_record_should_not_be_be_marked_after_reload
    @pirate.mark_for_destruction
    @pirate.ship.mark_for_destruction

    assert !@pirate.reload.marked_for_destruction?
    assert !@pirate.ship.reload.marked_for_destruction?
  end

  # has_one
  def test_should_destroy_a_child_association_as_part_of_the_save_transaction_if_it_was_marked_for_destruction
    assert !@pirate.ship.marked_for_destruction?

    @pirate.ship.mark_for_destruction
    id = @pirate.ship.id

    assert @pirate.ship.marked_for_destruction?
    assert Ship.find_by_id(id)

    @pirate.save
    assert_nil @pirate.reload.ship
    assert_nil Ship.find_by_id(id)
  end

  def test_should_skip_validation_on_a_child_association_if_marked_for_destruction
    @pirate.ship.name = ""
    assert !@pirate.valid?

    @pirate.ship.mark_for_destruction
    @pirate.ship.expects(:valid?).never
    assert_difference("Ship.count", -1) { @pirate.save! }
  end

  def test_a_child_marked_for_destruction_should_not_be_destroyed_twice
    @pirate.ship.mark_for_destruction
    assert @pirate.save
    class << @pirate.ship
      def destroy; raise "Should not be called" end
    end
    assert @pirate.save
  end

  def test_should_rollback_destructions_if_an_exception_occurred_while_saving_a_child
    # Stub the save method of the @pirate.ship instance to destroy and then raise an exception
    class << @pirate.ship
      def save(*args)
        super
        destroy
        raise "Oh noes!"
      end
    end

    @ship.pirate.catchphrase = "Changed Catchphrase"

    assert_raise(RuntimeError) { assert !@pirate.save }
    assert_not_nil @pirate.reload.ship
  end

  def test_should_save_changed_has_one_changed_object_if_child_is_saved
    @pirate.ship.name = "NewName"
    assert @pirate.save
    assert_equal "NewName", @pirate.ship.reload.name
  end

  def test_should_not_save_changed_has_one_unchanged_object_if_child_is_saved
    @pirate.ship.expects(:save).never
    assert @pirate.save
  end

  # belongs_to
  def test_should_destroy_a_parent_association_as_part_of_the_save_transaction_if_it_was_marked_for_destruction
    assert !@ship.pirate.marked_for_destruction?

    @ship.pirate.mark_for_destruction
    id = @ship.pirate.id

    assert @ship.pirate.marked_for_destruction?
    assert Pirate.find_by_id(id)

    @ship.save
    assert_nil @ship.reload.pirate
    assert_nil Pirate.find_by_id(id)
  end

  def test_should_skip_validation_on_a_parent_association_if_marked_for_destruction
    @ship.pirate.catchphrase = ""
    assert !@ship.valid?

    @ship.pirate.mark_for_destruction
    @ship.pirate.expects(:valid?).never
    assert_difference("Pirate.count", -1) { @ship.save! }
  end

  def test_a_parent_marked_for_destruction_should_not_be_destroyed_twice
    @ship.pirate.mark_for_destruction
    assert @ship.save
    class << @ship.pirate
      def destroy; raise "Should not be called" end
    end
    assert @ship.save
  end

  def test_should_rollback_destructions_if_an_exception_occurred_while_saving_a_parent
    # Stub the save method of the @ship.pirate instance to destroy and then raise an exception
    class << @ship.pirate
      def save(*args)
        super
        destroy
        raise "Oh noes!"
      end
    end

    @ship.pirate.catchphrase = "Changed Catchphrase"

    assert_raise(RuntimeError) { assert !@ship.save }
    assert_not_nil @ship.reload.pirate
  end

  def test_should_save_changed_child_objects_if_parent_is_saved
    @pirate = @ship.create_pirate(catchphrase: "Don' botharrr talkin' like one, savvy?")
    @parrot = @pirate.parrots.create!(name: "Posideons Killer")
    @parrot.name = "NewName"
    @ship.save

    assert_equal "NewName", @parrot.reload.name
  end

  def test_should_destroy_has_many_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
    2.times { |i| @pirate.birds.create!(name: "birds_#{i}") }

    assert !@pirate.birds.any?(&:marked_for_destruction?)

    @pirate.birds.each(&:mark_for_destruction)
    klass = @pirate.birds.first.class
    ids = @pirate.birds.map(&:id)

    assert @pirate.birds.all?(&:marked_for_destruction?)
    ids.each { |id| assert klass.find_by_id(id) }

    @pirate.save
    assert @pirate.reload.birds.empty?
    ids.each { |id| assert_nil klass.find_by_id(id) }
  end

  def test_should_not_resave_destroyed_association
    @pirate.birds.create!(name: :parrot)
    @pirate.birds.first.destroy
    @pirate.save!
    assert @pirate.reload.birds.empty?
  end

  def test_should_skip_validation_on_has_many_if_marked_for_destruction
    2.times { |i| @pirate.birds.create!(name: "birds_#{i}") }

    @pirate.birds.each { |bird| bird.name = "" }
    assert !@pirate.valid?

    @pirate.birds.each do |bird|
      bird.mark_for_destruction
      bird.expects(:valid?).never
    end
    assert_difference("Bird.count", -2) { @pirate.save! }
  end

  def test_should_skip_validation_on_has_many_if_destroyed
    @pirate.birds.create!(name: "birds_1")

    @pirate.birds.each { |bird| bird.name = "" }
    assert !@pirate.valid?

    @pirate.birds.each(&:destroy)
    assert @pirate.valid?
  end

  def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_has_many
    @pirate.birds.create!(name: "birds_1")

    @pirate.birds.each(&:mark_for_destruction)
    assert @pirate.save

    @pirate.birds.each { |bird| bird.expects(:destroy).never }
    assert @pirate.save
  end

  def test_should_rollback_destructions_if_an_exception_occurred_while_saving_has_many
    2.times { |i| @pirate.birds.create!(name: "birds_#{i}") }
    before = @pirate.birds.map { |c| c.mark_for_destruction ; c }

    # Stub the destroy method of the second child to raise an exception
    class << before.last
      def destroy(*args)
        super
        raise "Oh noes!"
      end
    end

    assert_raise(RuntimeError) { assert !@pirate.save }
    assert_equal before, @pirate.reload.birds
  end

  def test_when_new_record_a_child_marked_for_destruction_should_not_affect_other_records_from_saving
    @pirate = @ship.build_pirate(catchphrase: "Arr' now I shall keep me eye on you matey!") # new record

    3.times { |i| @pirate.birds.build(name: "birds_#{i}") }
    @pirate.birds[1].mark_for_destruction
    @pirate.save!

    assert_equal 2, @pirate.birds.reload.length
  end

  def test_should_save_new_record_that_has_same_value_as_existing_record_marked_for_destruction_on_field_that_has_unique_index
    Bird.connection.add_index :birds, :name, unique: true

    3.times { |i| @pirate.birds.create(name: "unique_birds_#{i}") }

    @pirate.birds[0].mark_for_destruction
    @pirate.birds.build(name: @pirate.birds[0].name)
    @pirate.save!

    assert_equal 3, @pirate.birds.reload.length
  ensure
    Bird.connection.remove_index :birds, column: :name
  end

  # Add and remove callbacks tests for association collections.
  %w{ method proc }.each do |callback_type|
    define_method("test_should_run_add_callback_#{callback_type}s_for_has_many") do
      association_name_with_callbacks = "birds_with_#{callback_type}_callbacks"

      pirate = Pirate.new(catchphrase: "Arr")
      pirate.send(association_name_with_callbacks).build(name: "Crowe the One-Eyed")

      expected = [
        "before_adding_#{callback_type}_bird_<new>",
        "after_adding_#{callback_type}_bird_<new>"
      ]

      assert_equal expected, pirate.ship_log
    end

    define_method("test_should_run_remove_callback_#{callback_type}s_for_has_many") do
      association_name_with_callbacks = "birds_with_#{callback_type}_callbacks"

      @pirate.send(association_name_with_callbacks).create!(name: "Crowe the One-Eyed")
      @pirate.send(association_name_with_callbacks).each(&:mark_for_destruction)
      child_id = @pirate.send(association_name_with_callbacks).first.id

      @pirate.ship_log.clear
      @pirate.save

      expected = [
        "before_removing_#{callback_type}_bird_#{child_id}",
        "after_removing_#{callback_type}_bird_#{child_id}"
      ]

      assert_equal expected, @pirate.ship_log
    end
  end

  def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
    2.times { |i| @pirate.parrots.create!(name: "parrots_#{i}") }

    assert !@pirate.parrots.any?(&:marked_for_destruction?)
    @pirate.parrots.each(&:mark_for_destruction)

    assert_no_difference "Parrot.count" do
      @pirate.save
    end

    assert @pirate.reload.parrots.empty?

    join_records = Pirate.connection.select_all("SELECT * FROM parrots_pirates WHERE pirate_id = #{@pirate.id}")
    assert join_records.empty?
  end

  def test_should_skip_validation_on_habtm_if_marked_for_destruction
    2.times { |i| @pirate.parrots.create!(name: "parrots_#{i}") }

    @pirate.parrots.each { |parrot| parrot.name = "" }
    assert !@pirate.valid?

    @pirate.parrots.each do |parrot|
      parrot.mark_for_destruction
      parrot.expects(:valid?).never
    end

    @pirate.save!
    assert @pirate.reload.parrots.empty?
  end

  def test_should_skip_validation_on_habtm_if_destroyed
    @pirate.parrots.create!(name: "parrots_1")

    @pirate.parrots.each { |parrot| parrot.name = "" }
    assert !@pirate.valid?

    @pirate.parrots.each(&:destroy)
    assert @pirate.valid?
  end

  def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_habtm
    @pirate.parrots.create!(name: "parrots_1")

    @pirate.parrots.each(&:mark_for_destruction)
    assert @pirate.save

    Pirate.transaction do
      assert_queries(0) do
        assert @pirate.save
      end
    end
  end

  def test_should_rollback_destructions_if_an_exception_occurred_while_saving_habtm
    2.times { |i| @pirate.parrots.create!(name: "parrots_#{i}") }
    before = @pirate.parrots.map { |c| c.mark_for_destruction ; c }

    class << @pirate.association(:parrots)
      def destroy(*args)
        super
        raise "Oh noes!"
      end
    end

    assert_raise(RuntimeError) { assert !@pirate.save }
    assert_equal before, @pirate.reload.parrots
  end

  # Add and remove callbacks tests for association collections.
  %w{ method proc }.each do |callback_type|
    define_method("test_should_run_add_callback_#{callback_type}s_for_habtm") do
      association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks"

      pirate = Pirate.new(catchphrase: "Arr")
      pirate.send(association_name_with_callbacks).build(name: "Crowe the One-Eyed")

      expected = [
        "before_adding_#{callback_type}_parrot_<new>",
        "after_adding_#{callback_type}_parrot_<new>"
      ]

      assert_equal expected, pirate.ship_log
    end

    define_method("test_should_run_remove_callback_#{callback_type}s_for_habtm") do
      association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks"

      @pirate.send(association_name_with_callbacks).create!(name: "Crowe the One-Eyed")
      @pirate.send(association_name_with_callbacks).each(&:mark_for_destruction)
      child_id = @pirate.send(association_name_with_callbacks).first.id

      @pirate.ship_log.clear
      @pirate.save

      expected = [
        "before_removing_#{callback_type}_parrot_#{child_id}",
        "after_removing_#{callback_type}_parrot_#{child_id}"
      ]

      assert_equal expected, @pirate.ship_log
    end
  end
end

class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
  self.use_transactional_tests = false unless supports_savepoints?

  def setup
    super
    @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
    @ship = @pirate.create_ship(name: "Nights Dirty Lightning")
  end

  def test_should_still_work_without_an_associated_model
    @ship.destroy
    @pirate.reload.catchphrase = "Arr"
    @pirate.save
    assert_equal "Arr", @pirate.reload.catchphrase
  end

  def test_should_automatically_save_the_associated_model
    @pirate.ship.name = "The Vile Insanity"
    @pirate.save
    assert_equal "The Vile Insanity", @pirate.reload.ship.name
  end

  def test_changed_for_autosave_should_handle_cycles
    @ship.pirate = @pirate
    assert_queries(0) { @ship.save! }

    @parrot = @pirate.parrots.create(name: "some_name")
    @parrot.name="changed_name"
    assert_queries(1) { @ship.save! }
    assert_queries(0) { @ship.save! }
  end

  def test_should_automatically_save_bang_the_associated_model
    @pirate.ship.name = "The Vile Insanity"
    @pirate.save!
    assert_equal "The Vile Insanity", @pirate.reload.ship.name
  end

  def test_should_automatically_validate_the_associated_model
    @pirate.ship.name = ""
    assert @pirate.invalid?
    assert @pirate.errors[:"ship.name"].any?
  end

  def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it_is_not_valid
    @pirate.ship.name   = nil
    @pirate.catchphrase = nil
    assert @pirate.invalid?
    assert @pirate.errors[:"ship.name"].any?
    assert @pirate.errors[:catchphrase].any?
  end

  def test_should_not_ignore_different_error_messages_on_the_same_attribute
    old_validators = Ship._validators.deep_dup
    old_callbacks = Ship._validate_callbacks.deep_dup
    Ship.validates_format_of :name, with: /\w/
    @pirate.ship.name   = ""
    @pirate.catchphrase = nil
    assert @pirate.invalid?
    assert_equal ["can't be blank", "is invalid"], @pirate.errors[:"ship.name"]
  ensure
    Ship._validators = old_validators if old_validators
    Ship._validate_callbacks = old_callbacks if old_callbacks
  end

  def test_should_still_allow_to_bypass_validations_on_the_associated_model
    @pirate.catchphrase = ""
    @pirate.ship.name = ""
    @pirate.save(validate: false)
    # Oracle saves empty string as NULL
    if current_adapter?(:OracleAdapter)
      assert_equal [nil, nil], [@pirate.reload.catchphrase, @pirate.ship.name]
    else
      assert_equal ["", ""], [@pirate.reload.catchphrase, @pirate.ship.name]
    end
  end

  def test_should_allow_to_bypass_validations_on_associated_models_at_any_depth
    2.times { |i| @pirate.ship.parts.create!(name: "part #{i}") }

    @pirate.catchphrase = ""
    @pirate.ship.name = ""
    @pirate.ship.parts.each { |part| part.name = "" }
    @pirate.save(validate: false)

    values = [@pirate.reload.catchphrase, @pirate.ship.name, *@pirate.ship.parts.map(&:name)]
    # Oracle saves empty string as NULL
    if current_adapter?(:OracleAdapter)
      assert_equal [nil, nil, nil, nil], values
    else
      assert_equal ["", "", "", ""], values
    end
  end

  def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
    @pirate.ship.name = ""
    assert_raise(ActiveRecord::RecordInvalid) do
      @pirate.save!
    end
  end

  def test_should_not_save_and_return_false_if_a_callback_cancelled_saving
    pirate = Pirate.new(catchphrase: "Arr")
    ship = pirate.build_ship(name: "The Vile Insanity")
    ship.cancel_save_from_callback = true

    assert_no_difference "Pirate.count" do
      assert_no_difference "Ship.count" do
        assert !pirate.save
      end
    end
  end

  def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
    before = [@pirate.catchphrase, @pirate.ship.name]

    @pirate.catchphrase = "Arr"
    @pirate.ship.name = "The Vile Insanity"

    # Stub the save method of the @pirate.ship instance to raise an exception
    class << @pirate.ship
      def save(*args)
        super
        raise "Oh noes!"
      end
    end

    assert_raise(RuntimeError) { assert !@pirate.save }
    assert_equal before, [@pirate.reload.catchphrase, @pirate.ship.name]
  end

  def test_should_not_load_the_associated_model
    assert_queries(1) { @pirate.catchphrase = "Arr"; @pirate.save! }
  end

  def test_mark_for_destruction_is_ignored_without_autosave_true
    ship = ShipWithoutNestedAttributes.new(name: "The Black Flag")
    ship.parts.build.mark_for_destruction

    assert_not ship.valid?
  end
end

class TestAutosaveAssociationOnAHasOneThroughAssociation < ActiveRecord::TestCase
  self.use_transactional_tests = false unless supports_savepoints?

  def setup
    super
    organization = Organization.create
    @member = Member.create
    MemberDetail.create(organization: organization, member: @member)
  end

  def test_should_not_has_one_through_model
    class << @member.organization
      def save(*args)
        super
        raise "Oh noes!"
      end
    end
    assert_nothing_raised { @member.save }
  end
end

class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
  self.use_transactional_tests = false unless supports_savepoints?

  def setup
    super
    @ship = Ship.create(name: "Nights Dirty Lightning")
    @pirate = @ship.create_pirate(catchphrase: "Don' botharrr talkin' like one, savvy?")
  end

  def test_should_still_work_without_an_associated_model
    @pirate.destroy
    @ship.reload.name = "The Vile Insanity"
    @ship.save
    assert_equal "The Vile Insanity", @ship.reload.name
  end

  def test_should_automatically_save_the_associated_model
    @ship.pirate.catchphrase = "Arr"
    @ship.save
    assert_equal "Arr", @ship.reload.pirate.catchphrase
  end

  def test_should_automatically_save_bang_the_associated_model
    @ship.pirate.catchphrase = "Arr"
    @ship.save!
    assert_equal "Arr", @ship.reload.pirate.catchphrase
  end

  def test_should_automatically_validate_the_associated_model
    @ship.pirate.catchphrase = ""
    assert @ship.invalid?
    assert @ship.errors[:"pirate.catchphrase"].any?
  end

  def test_should_merge_errors_on_the_associated_model_onto_the_parent_even_if_it_is_not_valid
    @ship.name = nil
    @ship.pirate.catchphrase = nil
    assert @ship.invalid?
    assert @ship.errors[:name].any?
    assert @ship.errors[:"pirate.catchphrase"].any?
  end

  def test_should_still_allow_to_bypass_validations_on_the_associated_model
    @ship.pirate.catchphrase = ""
    @ship.name = ""
    @ship.save(validate: false)
    # Oracle saves empty string as NULL
    if current_adapter?(:OracleAdapter)
      assert_equal [nil, nil], [@ship.reload.name, @ship.pirate.catchphrase]
    else
      assert_equal ["", ""], [@ship.reload.name, @ship.pirate.catchphrase]
    end
  end

  def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
    @ship.pirate.catchphrase = ""
    assert_raise(ActiveRecord::RecordInvalid) do
      @ship.save!
    end
  end

  def test_should_not_save_and_return_false_if_a_callback_cancelled_saving
    ship = Ship.new(name: "The Vile Insanity")
    pirate = ship.build_pirate(catchphrase: "Arr")
    pirate.cancel_save_from_callback = true

    assert_no_difference "Ship.count" do
      assert_no_difference "Pirate.count" do
        assert !ship.save
      end
    end
  end

  def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
    before = [@ship.pirate.catchphrase, @ship.name]

    @ship.pirate.catchphrase = "Arr"
    @ship.name = "The Vile Insanity"

    # Stub the save method of the @ship.pirate instance to raise an exception
    class << @ship.pirate
      def save(*args)
        super
        raise "Oh noes!"
      end
    end

    assert_raise(RuntimeError) { assert !@ship.save }
    assert_equal before, [@ship.pirate.reload.catchphrase, @ship.reload.name]
  end

  def test_should_not_load_the_associated_model
    assert_queries(1) { @ship.name = "The Vile Insanity"; @ship.save! }
  end
end

module AutosaveAssociationOnACollectionAssociationTests
  def test_should_automatically_save_the_associated_models
    new_names = ["Grace OMalley", "Privateers Greed"]
    @pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }

    @pirate.save
    assert_equal new_names, @pirate.reload.send(@association_name).map(&:name)
  end

  def test_should_automatically_save_bang_the_associated_models
    new_names = ["Grace OMalley", "Privateers Greed"]
    @pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }

    @pirate.save!
    assert_equal new_names, @pirate.reload.send(@association_name).map(&:name)
  end

  def test_should_update_children_when_autosave_is_true_and_parent_is_new_but_child_is_not
    parrot = Parrot.create!(name: "Polly")
    parrot.name = "Squawky"
    pirate = Pirate.new(parrots: [parrot], catchphrase: "Arrrr")

    pirate.save!

    assert_equal "Squawky", parrot.reload.name
  end

  def test_should_automatically_validate_the_associated_models
    @pirate.send(@association_name).each { |child| child.name = "" }

    assert !@pirate.valid?
    assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
    assert @pirate.errors[@association_name].empty?
  end

  def test_should_not_use_default_invalid_error_on_associated_models
    @pirate.send(@association_name).build(name: "")

    assert !@pirate.valid?
    assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
    assert @pirate.errors[@association_name].empty?
  end

  def test_should_default_invalid_error_from_i18n
    I18n.backend.store_translations(:en, activerecord: {errors: { models:
      { @associated_model_name.to_s.to_sym => { blank: "cannot be blank" } }
    }})

    @pirate.send(@association_name).build(name: "")

    assert !@pirate.valid?
    assert_equal ["cannot be blank"], @pirate.errors["#{@association_name}.name"]
    assert_equal ["#{@association_name.to_s.humanize} name cannot be blank"], @pirate.errors.full_messages
    assert @pirate.errors[@association_name].empty?
  ensure
    I18n.backend = I18n::Backend::Simple.new
  end

  def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it_is_not_valid
    @pirate.send(@association_name).each { |child| child.name = "" }
    @pirate.catchphrase = nil

    assert !@pirate.valid?
    assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
    assert @pirate.errors[:catchphrase].any?
  end

  def test_should_allow_to_bypass_validations_on_the_associated_models_on_update
    @pirate.catchphrase = ""
    @pirate.send(@association_name).each { |child| child.name = "" }

    assert @pirate.save(validate: false)
    # Oracle saves empty string as NULL
    if current_adapter?(:OracleAdapter)
      assert_equal [nil, nil, nil], [
        @pirate.reload.catchphrase,
        @pirate.send(@association_name).first.name,
        @pirate.send(@association_name).last.name
      ]
    else
      assert_equal ["", "", ""], [
        @pirate.reload.catchphrase,
        @pirate.send(@association_name).first.name,
        @pirate.send(@association_name).last.name
      ]
    end
  end

  def test_should_validation_the_associated_models_on_create
    assert_no_difference("#{ @association_name == :birds ? 'Bird' : 'Parrot' }.count") do
      2.times { @pirate.send(@association_name).build }
      @pirate.save
    end
  end

  def test_should_allow_to_bypass_validations_on_the_associated_models_on_create
    assert_difference("#{ @association_name == :birds ? 'Bird' : 'Parrot' }.count", 2) do
      2.times { @pirate.send(@association_name).build }
      @pirate.save(validate: false)
    end
  end

  def test_should_not_save_and_return_false_if_a_callback_cancelled_saving_in_either_create_or_update
    @pirate.catchphrase = "Changed"
    @child_1.name = "Changed"
    @child_1.cancel_save_from_callback = true

    assert !@pirate.save
    assert_equal "Don' botharrr talkin' like one, savvy?", @pirate.reload.catchphrase
    assert_equal "Posideons Killer", @child_1.reload.name

    new_pirate = Pirate.new(catchphrase: "Arr")
    new_child = new_pirate.send(@association_name).build(name: "Grace OMalley")
    new_child.cancel_save_from_callback = true

    assert_no_difference "Pirate.count" do
      assert_no_difference "#{new_child.class.name}.count" do
        assert !new_pirate.save
      end
    end
  end

  def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
    before = [@pirate.catchphrase, *@pirate.send(@association_name).map(&:name)]
    new_names = ["Grace OMalley", "Privateers Greed"]

    @pirate.catchphrase = "Arr"
    @pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }

    # Stub the save method of the first child instance to raise an exception
    class << @pirate.send(@association_name).first
      def save(*args)
        super
        raise "Oh noes!"
      end
    end

    assert_raise(RuntimeError) { assert !@pirate.save }
    assert_equal before, [@pirate.reload.catchphrase, *@pirate.send(@association_name).map(&:name)]
  end

  def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
    @pirate.send(@association_name).each { |child| child.name = "" }
    assert_raise(ActiveRecord::RecordInvalid) do
      @pirate.save!
    end
  end

  def test_should_not_load_the_associated_models_if_they_were_not_loaded_yet
    assert_queries(1) { @pirate.catchphrase = "Arr"; @pirate.save! }

    @pirate.send(@association_name).load_target

    assert_queries(3) do
      @pirate.catchphrase = "Yarr"
      new_names = ["Grace OMalley", "Privateers Greed"]
      @pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
      @pirate.save!
    end
  end
end

class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
  self.use_transactional_tests = false unless supports_savepoints?

  def setup
    super
    @association_name = :birds
    @associated_model_name = :bird

    @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
    @child_1 = @pirate.birds.create(name: "Posideons Killer")
    @child_2 = @pirate.birds.create(name: "Killer bandita Dionne")
  end

  include AutosaveAssociationOnACollectionAssociationTests
end

class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::TestCase
  self.use_transactional_tests = false unless supports_savepoints?

  def setup
    super
    @association_name = :autosaved_parrots
    @associated_model_name = :parrot
    @habtm = true

    @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
    @child_1 = @pirate.parrots.create(name: "Posideons Killer")
    @child_2 = @pirate.parrots.create(name: "Killer bandita Dionne")
  end

  include AutosaveAssociationOnACollectionAssociationTests
end

class TestAutosaveAssociationOnAHasAndBelongsToManyAssociationWithAcceptsNestedAttributes < ActiveRecord::TestCase
  self.use_transactional_tests = false unless supports_savepoints?

  def setup
    super
    @association_name = :parrots
    @associated_model_name = :parrot
    @habtm = true

    @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
    @child_1 = @pirate.parrots.create(name: "Posideons Killer")
    @child_2 = @pirate.parrots.create(name: "Killer bandita Dionne")
  end

  include AutosaveAssociationOnACollectionAssociationTests
end

class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::TestCase
  self.use_transactional_tests = false unless supports_savepoints?

  def setup
    super
    @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
    @pirate.birds.create(name: "cookoo")
  end

  test "should automatically validate associations" do
    assert @pirate.valid?
    @pirate.birds.each { |bird| bird.name = "" }

    assert !@pirate.valid?
  end
end

class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::TestCase
  self.use_transactional_tests = false unless supports_savepoints?

  def setup
    super
    @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
    @pirate.create_ship(name: "titanic")
    super
  end

  test "should automatically validate associations with :validate => true" do
    assert @pirate.valid?
    @pirate.ship.name = ""
    assert !@pirate.valid?
  end

  test "should not automatically add validate associations without :validate => true" do
    assert @pirate.valid?
    @pirate.non_validated_ship.name = ""
    assert @pirate.valid?
  end
end

class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::TestCase
  self.use_transactional_tests = false unless supports_savepoints?

  def setup
    super
    @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
  end

  test "should automatically validate associations with :validate => true" do
    assert @pirate.valid?
    @pirate.parrot = Parrot.new(name: "")
    assert !@pirate.valid?
  end

  test "should not automatically validate associations without :validate => true" do
    assert @pirate.valid?
    @pirate.non_validated_parrot = Parrot.new(name: "")
    assert @pirate.valid?
  end
end

class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::TestCase
  self.use_transactional_tests = false unless supports_savepoints?

  def setup
    super
    @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
  end

  test "should automatically validate associations with :validate => true" do
    assert @pirate.valid?
    @pirate.parrots = [ Parrot.new(name: "popuga") ]
    @pirate.parrots.each { |parrot| parrot.name = "" }
    assert !@pirate.valid?
  end

  test "should not automatically validate associations without :validate => true" do
    assert @pirate.valid?
    @pirate.non_validated_parrots = [ Parrot.new(name: "popuga") ]
    @pirate.non_validated_parrots.each { |parrot| parrot.name = "" }
    assert @pirate.valid?
  end
end

class TestAutosaveAssociationValidationMethodsGeneration < ActiveRecord::TestCase
  self.use_transactional_tests = false unless supports_savepoints?

  def setup
    super
    @pirate = Pirate.new
  end

  test "should generate validation methods for has_many associations" do
    assert_respond_to @pirate, :validate_associated_records_for_birds
  end

  test "should generate validation methods for has_one associations with :validate => true" do
    assert_respond_to @pirate, :validate_associated_records_for_ship
  end

  test "should not generate validation methods for has_one associations without :validate => true" do
    assert !@pirate.respond_to?(:validate_associated_records_for_non_validated_ship)
  end

  test "should generate validation methods for belongs_to associations with :validate => true" do
    assert_respond_to @pirate, :validate_associated_records_for_parrot
  end

  test "should not generate validation methods for belongs_to associations without :validate => true" do
    assert !@pirate.respond_to?(:validate_associated_records_for_non_validated_parrot)
  end

  test "should generate validation methods for HABTM associations with :validate => true" do
    assert_respond_to @pirate, :validate_associated_records_for_parrots
  end
end

class TestAutosaveAssociationWithTouch < ActiveRecord::TestCase
  def test_autosave_with_touch_should_not_raise_system_stack_error
    invoice = Invoice.create
    assert_nothing_raised { invoice.line_items.create(amount: 10) }
  end
end