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
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
|
require "cases/helper"
require 'models/post'
require 'models/author'
require 'models/topic'
require 'models/reply'
require 'models/category'
require 'models/company'
require 'models/customer'
require 'models/developer'
require 'models/project'
require 'models/default'
require 'models/auto_id'
require 'models/boolean'
require 'models/column_name'
require 'models/subscriber'
require 'models/keyboard'
require 'models/comment'
require 'models/minimalistic'
require 'models/warehouse_thing'
require 'models/parrot'
require 'models/person'
require 'models/edge'
require 'models/joke'
require 'models/bulb'
require 'models/bird'
require 'models/teapot'
require 'rexml/document'
require 'active_support/core_ext/exception'
require 'bcrypt'
class FirstAbstractClass < ActiveRecord::Base
self.abstract_class = true
end
class SecondAbstractClass < FirstAbstractClass
self.abstract_class = true
end
class Photo < SecondAbstractClass; end
class Category < ActiveRecord::Base; end
class Categorization < ActiveRecord::Base; end
class Smarts < ActiveRecord::Base; end
class CreditCard < ActiveRecord::Base
class PinNumber < ActiveRecord::Base
class CvvCode < ActiveRecord::Base; end
class SubCvvCode < CvvCode; end
end
class SubPinNumber < PinNumber; end
class Brand < Category; end
end
class MasterCreditCard < ActiveRecord::Base; end
class Post < ActiveRecord::Base; end
class Computer < ActiveRecord::Base; end
class NonExistentTable < ActiveRecord::Base; end
class TestOracleDefault < ActiveRecord::Base; end
class ReadonlyTitlePost < Post
attr_readonly :title
end
class ProtectedTitlePost < Post
attr_protected :title
end
class Weird < ActiveRecord::Base; end
class Boolean < ActiveRecord::Base
def has_fun
super
end
end
class LintTest < ActiveRecord::TestCase
include ActiveModel::Lint::Tests
class LintModel < ActiveRecord::Base; end
def setup
@model = LintModel.new
end
end
class BasicsTest < ActiveRecord::TestCase
fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts
def test_generated_methods_modules
modules = Computer.ancestors
assert modules.include?(Computer::GeneratedFeatureMethods)
assert_equal(Computer::GeneratedFeatureMethods, Computer.generated_feature_methods)
assert(modules.index(Computer.generated_attribute_methods) > modules.index(Computer.generated_feature_methods),
"generated_attribute_methods must be higher in inheritance hierarchy than generated_feature_methods")
assert_not_equal Computer.generated_feature_methods, Post.generated_feature_methods
assert(modules.index(Computer.generated_attribute_methods) < modules.index(ActiveRecord::Base.ancestors[1]))
end
def test_column_names_are_escaped
conn = ActiveRecord::Base.connection
classname = conn.class.name[/[^:]*$/]
badchar = {
'SQLite3Adapter' => '"',
'MysqlAdapter' => '`',
'Mysql2Adapter' => '`',
'PostgreSQLAdapter' => '"',
'OracleAdapter' => '"',
}.fetch(classname) {
raise "need a bad char for #{classname}"
}
quoted = conn.quote_column_name "foo#{badchar}bar"
if current_adapter?(:OracleAdapter)
# Oracle does not allow double quotes in table and column names at all
# therefore quoting removes them
assert_equal("#{badchar}foobar#{badchar}", quoted)
else
assert_equal("#{badchar}foo#{badchar * 2}bar#{badchar}", quoted)
end
end
def test_columns_should_obey_set_primary_key
pk = Subscriber.columns.find { |x| x.name == 'nick' }
assert pk.primary, 'nick should be primary key'
end
def test_primary_key_with_no_id
assert_nil Edge.primary_key
end
unless current_adapter?(:PostgreSQLAdapter,:OracleAdapter,:SQLServerAdapter)
def test_limit_with_comma
assert_nothing_raised do
Topic.limit("1,2").all
end
end
end
def test_limit_without_comma
assert_nothing_raised do
assert_equal 1, Topic.limit("1").all.length
end
assert_nothing_raised do
assert_equal 1, Topic.limit(1).all.length
end
end
def test_invalid_limit
assert_raises(ArgumentError) do
Topic.limit("asdfadf").all
end
end
def test_limit_should_sanitize_sql_injection_for_limit_without_comas
assert_raises(ArgumentError) do
Topic.limit("1 select * from schema").all
end
end
def test_limit_should_sanitize_sql_injection_for_limit_with_comas
assert_raises(ArgumentError) do
Topic.limit("1, 7 procedure help()").all
end
end
unless current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter)
def test_limit_should_allow_sql_literal
assert_equal 1, Topic.limit(Arel.sql('2-1')).all.length
end
end
def test_select_symbol
topic_ids = Topic.select(:id).map(&:id).sort
assert_equal Topic.pluck(:id).sort, topic_ids
end
def test_table_exists
assert !NonExistentTable.table_exists?
assert Topic.table_exists?
end
def test_preserving_date_objects
if current_adapter?(:SybaseAdapter)
# Sybase ctlib does not (yet?) support the date type; use datetime instead.
assert_kind_of(
Time, Topic.find(1).last_read,
"The last_read attribute should be of the Time class"
)
else
# Oracle enhanced adapter allows to define Date attributes in model class (see topic.rb)
assert_kind_of(
Date, Topic.find(1).last_read,
"The last_read attribute should be of the Date class"
)
end
end
def test_previously_changed
topic = Topic.first
topic.title = '<3<3<3'
assert_equal({}, topic.previous_changes)
topic.save!
expected = ["The First Topic", "<3<3<3"]
assert_equal(expected, topic.previous_changes['title'])
end
def test_previously_changed_dup
topic = Topic.first
topic.title = '<3<3<3'
topic.save!
t2 = topic.dup
assert_equal(topic.previous_changes, t2.previous_changes)
topic.title = "lolwut"
topic.save!
assert_not_equal(topic.previous_changes, t2.previous_changes)
end
def test_preserving_time_objects
assert_kind_of(
Time, Topic.find(1).bonus_time,
"The bonus_time attribute should be of the Time class"
)
assert_kind_of(
Time, Topic.find(1).written_on,
"The written_on attribute should be of the Time class"
)
# For adapters which support microsecond resolution.
if current_adapter?(:PostgreSQLAdapter) || current_adapter?(:SQLiteAdapter)
assert_equal 11, Topic.find(1).written_on.sec
assert_equal 223300, Topic.find(1).written_on.usec
assert_equal 9900, Topic.find(2).written_on.usec
end
end
def test_preserving_time_objects_with_local_time_conversion_to_default_timezone_utc
with_env_tz 'America/New_York' do
with_active_record_default_timezone :utc do
time = Time.local(2000)
topic = Topic.create('written_on' => time)
saved_time = Topic.find(topic.id).reload.written_on
assert_equal time, saved_time
assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "EST"], time.to_a
assert_equal [0, 0, 5, 1, 1, 2000, 6, 1, false, "UTC"], saved_time.to_a
end
end
end
def test_preserving_time_objects_with_time_with_zone_conversion_to_default_timezone_utc
with_env_tz 'America/New_York' do
with_active_record_default_timezone :utc do
Time.use_zone 'Central Time (US & Canada)' do
time = Time.zone.local(2000)
topic = Topic.create('written_on' => time)
saved_time = Topic.find(topic.id).reload.written_on
assert_equal time, saved_time
assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "CST"], time.to_a
assert_equal [0, 0, 6, 1, 1, 2000, 6, 1, false, "UTC"], saved_time.to_a
end
end
end
end
def test_preserving_time_objects_with_utc_time_conversion_to_default_timezone_local
with_env_tz 'America/New_York' do
time = Time.utc(2000)
topic = Topic.create('written_on' => time)
saved_time = Topic.find(topic.id).reload.written_on
assert_equal time, saved_time
assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "UTC"], time.to_a
assert_equal [0, 0, 19, 31, 12, 1999, 5, 365, false, "EST"], saved_time.to_a
end
end
def test_preserving_time_objects_with_time_with_zone_conversion_to_default_timezone_local
with_env_tz 'America/New_York' do
with_active_record_default_timezone :local do
Time.use_zone 'Central Time (US & Canada)' do
time = Time.zone.local(2000)
topic = Topic.create('written_on' => time)
saved_time = Topic.find(topic.id).reload.written_on
assert_equal time, saved_time
assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "CST"], time.to_a
assert_equal [0, 0, 1, 1, 1, 2000, 6, 1, false, "EST"], saved_time.to_a
end
end
end
end
def test_custom_mutator
topic = Topic.find(1)
# This mutator is protected in the class definition
topic.send(:approved=, true)
assert topic.instance_variable_get("@custom_approved")
end
def test_initialize_with_attributes
topic = Topic.new({
"title" => "initialized from attributes", "written_on" => "2003-12-12 23:23"
})
assert_equal("initialized from attributes", topic.title)
end
def test_initialize_with_invalid_attribute
begin
Topic.new({ "title" => "test",
"last_read(1i)" => "2005", "last_read(2i)" => "2", "last_read(3i)" => "31"})
rescue ActiveRecord::MultiparameterAssignmentErrors => ex
assert_equal(1, ex.errors.size)
assert_equal("last_read", ex.errors[0].attribute)
end
end
def test_create_after_initialize_without_block
cb = CustomBulb.create(:name => 'Dude')
assert_equal('Dude', cb.name)
assert_equal(true, cb.frickinawesome)
end
def test_create_after_initialize_with_block
cb = CustomBulb.create {|c| c.name = 'Dude' }
assert_equal('Dude', cb.name)
assert_equal(true, cb.frickinawesome)
end
def test_first_or_create
parrot = Bird.first_or_create(:color => 'green', :name => 'parrot')
assert parrot.persisted?
the_same_parrot = Bird.first_or_create(:color => 'yellow', :name => 'macaw')
assert_equal parrot, the_same_parrot
end
def test_first_or_create_bang
assert_raises(ActiveRecord::RecordInvalid) { Bird.first_or_create! }
parrot = Bird.first_or_create!(:color => 'green', :name => 'parrot')
assert parrot.persisted?
the_same_parrot = Bird.first_or_create!(:color => 'yellow', :name => 'macaw')
assert_equal parrot, the_same_parrot
end
def test_first_or_initialize
parrot = Bird.first_or_initialize(:color => 'green', :name => 'parrot')
assert_kind_of Bird, parrot
assert !parrot.persisted?
assert parrot.new_record?
assert parrot.valid?
end
def test_load
topics = Topic.find(:all, :order => 'id')
assert_equal(4, topics.size)
assert_equal(topics(:first).title, topics.first.title)
end
def test_load_with_condition
topics = Topic.find(:all, :conditions => "author_name = 'Mary'")
assert_equal(1, topics.size)
assert_equal(topics(:second).title, topics.first.title)
end
GUESSED_CLASSES = [Category, Smarts, CreditCard, CreditCard::PinNumber, CreditCard::PinNumber::CvvCode, CreditCard::SubPinNumber, CreditCard::Brand, MasterCreditCard]
def test_table_name_guesses
assert_equal "topics", Topic.table_name
assert_equal "categories", Category.table_name
assert_equal "smarts", Smarts.table_name
assert_equal "credit_cards", CreditCard.table_name
assert_equal "credit_card_pin_numbers", CreditCard::PinNumber.table_name
assert_equal "credit_card_pin_number_cvv_codes", CreditCard::PinNumber::CvvCode.table_name
assert_equal "credit_card_pin_numbers", CreditCard::SubPinNumber.table_name
assert_equal "categories", CreditCard::Brand.table_name
assert_equal "master_credit_cards", MasterCreditCard.table_name
ensure
GUESSED_CLASSES.each(&:reset_table_name)
end
def test_singular_table_name_guesses
ActiveRecord::Base.pluralize_table_names = false
GUESSED_CLASSES.each(&:reset_table_name)
assert_equal "category", Category.table_name
assert_equal "smarts", Smarts.table_name
assert_equal "credit_card", CreditCard.table_name
assert_equal "credit_card_pin_number", CreditCard::PinNumber.table_name
assert_equal "credit_card_pin_number_cvv_code", CreditCard::PinNumber::CvvCode.table_name
assert_equal "credit_card_pin_number", CreditCard::SubPinNumber.table_name
assert_equal "category", CreditCard::Brand.table_name
assert_equal "master_credit_card", MasterCreditCard.table_name
ensure
ActiveRecord::Base.pluralize_table_names = true
GUESSED_CLASSES.each(&:reset_table_name)
end
def test_table_name_guesses_with_prefixes_and_suffixes
ActiveRecord::Base.table_name_prefix = "test_"
Category.reset_table_name
assert_equal "test_categories", Category.table_name
ActiveRecord::Base.table_name_suffix = "_test"
Category.reset_table_name
assert_equal "test_categories_test", Category.table_name
ActiveRecord::Base.table_name_prefix = ""
Category.reset_table_name
assert_equal "categories_test", Category.table_name
ActiveRecord::Base.table_name_suffix = ""
Category.reset_table_name
assert_equal "categories", Category.table_name
ensure
ActiveRecord::Base.table_name_prefix = ""
ActiveRecord::Base.table_name_suffix = ""
GUESSED_CLASSES.each(&:reset_table_name)
end
def test_singular_table_name_guesses_with_prefixes_and_suffixes
ActiveRecord::Base.pluralize_table_names = false
ActiveRecord::Base.table_name_prefix = "test_"
Category.reset_table_name
assert_equal "test_category", Category.table_name
ActiveRecord::Base.table_name_suffix = "_test"
Category.reset_table_name
assert_equal "test_category_test", Category.table_name
ActiveRecord::Base.table_name_prefix = ""
Category.reset_table_name
assert_equal "category_test", Category.table_name
ActiveRecord::Base.table_name_suffix = ""
Category.reset_table_name
assert_equal "category", Category.table_name
ensure
ActiveRecord::Base.pluralize_table_names = true
ActiveRecord::Base.table_name_prefix = ""
ActiveRecord::Base.table_name_suffix = ""
GUESSED_CLASSES.each(&:reset_table_name)
end
def test_table_name_guesses_with_inherited_prefixes_and_suffixes
GUESSED_CLASSES.each(&:reset_table_name)
CreditCard.table_name_prefix = "test_"
CreditCard.reset_table_name
Category.reset_table_name
assert_equal "test_credit_cards", CreditCard.table_name
assert_equal "categories", Category.table_name
CreditCard.table_name_suffix = "_test"
CreditCard.reset_table_name
Category.reset_table_name
assert_equal "test_credit_cards_test", CreditCard.table_name
assert_equal "categories", Category.table_name
CreditCard.table_name_prefix = ""
CreditCard.reset_table_name
Category.reset_table_name
assert_equal "credit_cards_test", CreditCard.table_name
assert_equal "categories", Category.table_name
CreditCard.table_name_suffix = ""
CreditCard.reset_table_name
Category.reset_table_name
assert_equal "credit_cards", CreditCard.table_name
assert_equal "categories", Category.table_name
ensure
CreditCard.table_name_prefix = ""
CreditCard.table_name_suffix = ""
GUESSED_CLASSES.each(&:reset_table_name)
end
def test_singular_table_name_guesses_for_individual_table
CreditCard.pluralize_table_names = false
CreditCard.reset_table_name
assert_equal "credit_card", CreditCard.table_name
assert_equal "categories", Category.table_name
ensure
CreditCard.pluralize_table_names = true
CreditCard.reset_table_name
end
if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
def test_update_all_with_order_and_limit
assert_equal 1, Topic.update_all("content = 'bulk updated!'", nil, :limit => 1, :order => 'id DESC')
end
end
def test_null_fields
assert_nil Topic.find(1).parent_id
assert_nil Topic.create("title" => "Hey you").parent_id
end
def test_default_values
topic = Topic.new
assert topic.approved?
assert_nil topic.written_on
assert_nil topic.bonus_time
assert_nil topic.last_read
topic.save
topic = Topic.find(topic.id)
assert topic.approved?
assert_nil topic.last_read
# Oracle has some funky default handling, so it requires a bit of
# extra testing. See ticket #2788.
if current_adapter?(:OracleAdapter)
test = TestOracleDefault.new
assert_equal "X", test.test_char
assert_equal "hello", test.test_string
assert_equal 3, test.test_int
end
end
# Oracle, and Sybase do not have a TIME datatype.
unless current_adapter?(:OracleAdapter, :SybaseAdapter)
def test_utc_as_time_zone
Topic.default_timezone = :utc
attributes = { "bonus_time" => "5:42:00AM" }
topic = Topic.find(1)
topic.attributes = attributes
assert_equal Time.utc(2000, 1, 1, 5, 42, 0), topic.bonus_time
Topic.default_timezone = :local
end
def test_utc_as_time_zone_and_new
Topic.default_timezone = :utc
attributes = { "bonus_time(1i)"=>"2000",
"bonus_time(2i)"=>"1",
"bonus_time(3i)"=>"1",
"bonus_time(4i)"=>"10",
"bonus_time(5i)"=>"35",
"bonus_time(6i)"=>"50" }
topic = Topic.new(attributes)
assert_equal Time.utc(2000, 1, 1, 10, 35, 50), topic.bonus_time
Topic.default_timezone = :local
end
end
def test_default_values_on_empty_strings
topic = Topic.new
topic.approved = nil
topic.last_read = nil
topic.save
topic = Topic.find(topic.id)
assert_nil topic.last_read
# Sybase adapter does not allow nulls in boolean columns
if current_adapter?(:SybaseAdapter)
assert topic.approved == false
else
assert_nil topic.approved
end
end
def test_equality
assert_equal Topic.find(1), Topic.find(2).topic
end
def test_find_by_slug
assert_equal Topic.find('1-meowmeow'), Topic.find(1)
end
def test_equality_of_new_records
assert_not_equal Topic.new, Topic.new
end
def test_equality_of_destroyed_records
topic_1 = Topic.new(:title => 'test_1')
topic_1.save
topic_2 = Topic.find(topic_1.id)
topic_1.destroy
assert_equal topic_1, topic_2
assert_equal topic_2, topic_1
end
def test_hashing
assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ]
end
def test_comparison
topic_1 = Topic.create!
topic_2 = Topic.create!
assert_equal [topic_2, topic_1].sort, [topic_1, topic_2]
end
def test_comparison_with_different_objects
topic = Topic.create
category = Category.create(:name => "comparison")
assert_nil topic <=> category
end
def test_readonly_attributes
assert_equal Set.new([ 'title' , 'comments_count' ]), ReadonlyTitlePost.readonly_attributes
post = ReadonlyTitlePost.create(:title => "cannot change this", :body => "changeable")
post.reload
assert_equal "cannot change this", post.title
post.update_attributes(:title => "try to change", :body => "changed")
post.reload
assert_equal "cannot change this", post.title
assert_equal "changed", post.body
end
def test_non_valid_identifier_column_name
weird = Weird.create('a$b' => 'value')
weird.reload
assert_equal 'value', weird.send('a$b')
assert_equal 'value', weird.read_attribute('a$b')
weird.update_column('a$b', 'value2')
weird.reload
assert_equal 'value2', weird.send('a$b')
assert_equal 'value2', weird.read_attribute('a$b')
end
def test_multiparameter_attributes_on_date
attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "24" }
topic = Topic.find(1)
topic.attributes = attributes
# note that extra #to_date call allows test to pass for Oracle, which
# treats dates/times the same
assert_date_from_db Date.new(2004, 6, 24), topic.last_read.to_date
end
def test_multiparameter_attributes_on_date_with_empty_year
attributes = { "last_read(1i)" => "", "last_read(2i)" => "6", "last_read(3i)" => "24" }
topic = Topic.find(1)
topic.attributes = attributes
# note that extra #to_date call allows test to pass for Oracle, which
# treats dates/times the same
assert_nil topic.last_read
end
def test_multiparameter_attributes_on_date_with_empty_month
attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "", "last_read(3i)" => "24" }
topic = Topic.find(1)
topic.attributes = attributes
# note that extra #to_date call allows test to pass for Oracle, which
# treats dates/times the same
assert_nil topic.last_read
end
def test_multiparameter_attributes_on_date_with_empty_day
attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "" }
topic = Topic.find(1)
topic.attributes = attributes
# note that extra #to_date call allows test to pass for Oracle, which
# treats dates/times the same
assert_nil topic.last_read
end
def test_multiparameter_attributes_on_date_with_empty_day_and_year
attributes = { "last_read(1i)" => "", "last_read(2i)" => "6", "last_read(3i)" => "" }
topic = Topic.find(1)
topic.attributes = attributes
# note that extra #to_date call allows test to pass for Oracle, which
# treats dates/times the same
assert_nil topic.last_read
end
def test_multiparameter_attributes_on_date_with_empty_day_and_month
attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "", "last_read(3i)" => "" }
topic = Topic.find(1)
topic.attributes = attributes
# note that extra #to_date call allows test to pass for Oracle, which
# treats dates/times the same
assert_nil topic.last_read
end
def test_multiparameter_attributes_on_date_with_empty_year_and_month
attributes = { "last_read(1i)" => "", "last_read(2i)" => "", "last_read(3i)" => "24" }
topic = Topic.find(1)
topic.attributes = attributes
# note that extra #to_date call allows test to pass for Oracle, which
# treats dates/times the same
assert_nil topic.last_read
end
def test_multiparameter_attributes_on_date_with_all_empty
attributes = { "last_read(1i)" => "", "last_read(2i)" => "", "last_read(3i)" => "" }
topic = Topic.find(1)
topic.attributes = attributes
assert_nil topic.last_read
end
def test_multiparameter_attributes_on_time
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
}
topic = Topic.find(1)
topic.attributes = attributes
assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on
end
def test_multiparameter_attributes_on_time_with_no_date
ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
attributes = {
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
}
topic = Topic.find(1)
topic.attributes = attributes
end
assert_equal("written_on", ex.errors[0].attribute)
end
def test_multiparameter_attributes_on_time_with_invalid_time_params
ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "2004", "written_on(5i)" => "36", "written_on(6i)" => "64",
}
topic = Topic.find(1)
topic.attributes = attributes
end
assert_equal("written_on", ex.errors[0].attribute)
end
def test_multiparameter_attributes_on_time_with_old_date
attributes = {
"written_on(1i)" => "1850", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
}
topic = Topic.find(1)
topic.attributes = attributes
# testing against to_s(:db) representation because either a Time or a DateTime might be returned, depending on platform
assert_equal "1850-06-24 16:24:00", topic.written_on.to_s(:db)
end
def test_multiparameter_attributes_on_time_will_raise_on_big_time_if_missing_date_parts
ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
attributes = {
"written_on(4i)" => "16", "written_on(5i)" => "24"
}
topic = Topic.find(1)
topic.attributes = attributes
end
assert_equal("written_on", ex.errors[0].attribute)
end
def test_multiparameter_attributes_on_time_with_raise_on_small_time_if_missing_date_parts
ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
attributes = {
"written_on(4i)" => "16", "written_on(5i)" => "12", "written_on(6i)" => "02"
}
topic = Topic.find(1)
topic.attributes = attributes
end
assert_equal("written_on", ex.errors[0].attribute)
end
def test_multiparameter_attributes_on_time_will_ignore_hour_if_missing
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "12", "written_on(3i)" => "12",
"written_on(5i)" => "12", "written_on(6i)" => "02"
}
topic = Topic.find(1)
topic.attributes = attributes
assert_equal Time.local(2004, 12, 12, 0, 12, 2), topic.written_on
end
def test_multiparameter_attributes_on_time_will_ignore_hour_if_blank
attributes = {
"written_on(1i)" => "", "written_on(2i)" => "", "written_on(3i)" => "",
"written_on(4i)" => "", "written_on(5i)" => "12", "written_on(6i)" => "02"
}
topic = Topic.find(1)
topic.attributes = attributes
assert_nil topic.written_on
end
def test_multiparameter_attributes_on_time_will_ignore_date_if_empty
attributes = {
"written_on(1i)" => "", "written_on(2i)" => "", "written_on(3i)" => "",
"written_on(4i)" => "16", "written_on(5i)" => "24"
}
topic = Topic.find(1)
topic.attributes = attributes
assert_nil topic.written_on
end
def test_multiparameter_attributes_on_time_with_seconds_will_ignore_date_if_empty
attributes = {
"written_on(1i)" => "", "written_on(2i)" => "", "written_on(3i)" => "",
"written_on(4i)" => "16", "written_on(5i)" => "12", "written_on(6i)" => "02"
}
topic = Topic.find(1)
topic.attributes = attributes
assert_nil topic.written_on
end
def test_multiparameter_attributes_on_time_with_utc
ActiveRecord::Base.default_timezone = :utc
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
}
topic = Topic.find(1)
topic.attributes = attributes
assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on
ensure
ActiveRecord::Base.default_timezone = :local
end
def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.default_timezone = :utc
Time.zone = ActiveSupport::TimeZone[-28800]
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
}
topic = Topic.find(1)
topic.attributes = attributes
assert_equal Time.utc(2004, 6, 24, 23, 24, 0), topic.written_on
assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on.time
assert_equal Time.zone, topic.written_on.time_zone
ensure
ActiveRecord::Base.time_zone_aware_attributes = false
ActiveRecord::Base.default_timezone = :local
Time.zone = nil
end
def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes_false
ActiveRecord::Base.time_zone_aware_attributes = false
Time.zone = ActiveSupport::TimeZone[-28800]
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
}
topic = Topic.find(1)
topic.attributes = attributes
assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
assert_equal false, topic.written_on.respond_to?(:time_zone)
ensure
Time.zone = nil
end
def test_multiparameter_attributes_on_time_with_skip_time_zone_conversion_for_attributes
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.default_timezone = :utc
Time.zone = ActiveSupport::TimeZone[-28800]
Topic.skip_time_zone_conversion_for_attributes = [:written_on]
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
}
topic = Topic.find(1)
topic.attributes = attributes
assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on
assert_equal false, topic.written_on.respond_to?(:time_zone)
ensure
ActiveRecord::Base.time_zone_aware_attributes = false
ActiveRecord::Base.default_timezone = :local
Time.zone = nil
Topic.skip_time_zone_conversion_for_attributes = []
end
# Oracle, and Sybase do not have a TIME datatype.
unless current_adapter?(:OracleAdapter, :SybaseAdapter)
def test_multiparameter_attributes_on_time_only_column_with_time_zone_aware_attributes_does_not_do_time_zone_conversion
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.default_timezone = :utc
Time.zone = ActiveSupport::TimeZone[-28800]
attributes = {
"bonus_time(1i)" => "2000", "bonus_time(2i)" => "1", "bonus_time(3i)" => "1",
"bonus_time(4i)" => "16", "bonus_time(5i)" => "24"
}
topic = Topic.find(1)
topic.attributes = attributes
assert_equal Time.utc(2000, 1, 1, 16, 24, 0), topic.bonus_time
assert topic.bonus_time.utc?
ensure
ActiveRecord::Base.time_zone_aware_attributes = false
ActiveRecord::Base.default_timezone = :local
Time.zone = nil
end
end
def test_multiparameter_attributes_on_time_with_empty_seconds
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => ""
}
topic = Topic.find(1)
topic.attributes = attributes
assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
end
def test_multiparameter_assignment_of_aggregation
customer = Customer.new
address = Address.new("The Street", "The City", "The Country")
attributes = { "address(1)" => address.street, "address(2)" => address.city, "address(3)" => address.country }
customer.attributes = attributes
assert_equal address, customer.address
end
def test_multiparameter_assignment_of_aggregation_out_of_order
customer = Customer.new
address = Address.new("The Street", "The City", "The Country")
attributes = { "address(3)" => address.country, "address(2)" => address.city, "address(1)" => address.street }
customer.attributes = attributes
assert_equal address, customer.address
end
def test_multiparameter_assignment_of_aggregation_with_missing_values
ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
customer = Customer.new
address = Address.new("The Street", "The City", "The Country")
attributes = { "address(2)" => address.city, "address(3)" => address.country }
customer.attributes = attributes
end
assert_equal("address", ex.errors[0].attribute)
end
def test_multiparameter_assignment_of_aggregation_with_blank_values
customer = Customer.new
address = Address.new("The Street", "The City", "The Country")
attributes = { "address(1)" => "", "address(2)" => address.city, "address(3)" => address.country }
customer.attributes = attributes
assert_equal Address.new(nil, "The City", "The Country"), customer.address
end
def test_multiparameter_assignment_of_aggregation_with_large_index
ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
customer = Customer.new
address = Address.new("The Street", "The City", "The Country")
attributes = { "address(1)" => "The Street", "address(2)" => address.city, "address(3000)" => address.country }
customer.attributes = attributes
end
assert_equal("address", ex.errors[0].attribute)
end
def test_attributes_on_dummy_time
# Oracle, and Sybase do not have a TIME datatype.
return true if current_adapter?(:OracleAdapter, :SybaseAdapter)
attributes = {
"bonus_time" => "5:42:00AM"
}
topic = Topic.find(1)
topic.attributes = attributes
assert_equal Time.utc(2000, 1, 1, 5, 42, 0), topic.bonus_time
end
def test_boolean
b_nil = Boolean.create({ "value" => nil })
nil_id = b_nil.id
b_false = Boolean.create({ "value" => false })
false_id = b_false.id
b_true = Boolean.create({ "value" => true })
true_id = b_true.id
b_nil = Boolean.find(nil_id)
assert_nil b_nil.value
b_false = Boolean.find(false_id)
assert !b_false.value?
b_true = Boolean.find(true_id)
assert b_true.value?
end
def test_boolean_without_questionmark
b_true = Boolean.create({ "value" => true })
true_id = b_true.id
subclass = Class.new(Boolean).find true_id
superclass = Boolean.find true_id
assert_equal superclass.read_attribute(:has_fun), subclass.read_attribute(:has_fun)
end
def test_boolean_cast_from_string
b_blank = Boolean.create({ "value" => "" })
blank_id = b_blank.id
b_false = Boolean.create({ "value" => "0" })
false_id = b_false.id
b_true = Boolean.create({ "value" => "1" })
true_id = b_true.id
b_blank = Boolean.find(blank_id)
assert_nil b_blank.value
b_false = Boolean.find(false_id)
assert !b_false.value?
b_true = Boolean.find(true_id)
assert b_true.value?
end
def test_new_record_returns_boolean
assert_equal false, Topic.new.persisted?
assert_equal true, Topic.find(1).persisted?
end
def test_dup
topic = Topic.find(1)
duped_topic = nil
assert_nothing_raised { duped_topic = topic.dup }
assert_equal topic.title, duped_topic.title
assert !duped_topic.persisted?
# test if the attributes have been duped
topic.title = "a"
duped_topic.title = "b"
assert_equal "a", topic.title
assert_equal "b", duped_topic.title
# test if the attribute values have been duped
duped_topic = topic.dup
duped_topic.title.replace "c"
assert_equal "a", topic.title
# test if attributes set as part of after_initialize are duped correctly
assert_equal topic.author_email_address, duped_topic.author_email_address
# test if saved clone object differs from original
duped_topic.save
assert duped_topic.persisted?
assert_not_equal duped_topic.id, topic.id
duped_topic.reload
assert_equal("c", duped_topic.title)
end
def test_dup_with_aggregate_of_same_name_as_attribute
dev = DeveloperWithAggregate.find(1)
assert_kind_of DeveloperSalary, dev.salary
dup = nil
assert_nothing_raised { dup = dev.dup }
assert_kind_of DeveloperSalary, dup.salary
assert_equal dev.salary.amount, dup.salary.amount
assert !dup.persisted?
# test if the attributes have been dupd
original_amount = dup.salary.amount
dev.salary.amount = 1
assert_equal original_amount, dup.salary.amount
assert dup.save
assert dup.persisted?
assert_not_equal dup.id, dev.id
end
def test_dup_does_not_copy_associations
author = authors(:david)
assert_not_equal [], author.posts
author.send(:clear_association_cache)
author_dup = author.dup
assert_equal [], author_dup.posts
end
def test_clone_preserves_subtype
clone = nil
assert_nothing_raised { clone = Company.find(3).clone }
assert_kind_of Client, clone
end
def test_clone_of_new_object_with_defaults
developer = Developer.new
assert !developer.name_changed?
assert !developer.salary_changed?
cloned_developer = developer.clone
assert !cloned_developer.name_changed?
assert !cloned_developer.salary_changed?
end
def test_clone_of_new_object_marks_attributes_as_dirty
developer = Developer.new :name => 'Bjorn', :salary => 100000
assert developer.name_changed?
assert developer.salary_changed?
cloned_developer = developer.clone
assert cloned_developer.name_changed?
assert cloned_developer.salary_changed?
end
def test_clone_of_new_object_marks_as_dirty_only_changed_attributes
developer = Developer.new :name => 'Bjorn'
assert developer.name_changed? # obviously
assert !developer.salary_changed? # attribute has non-nil default value, so treated as not changed
cloned_developer = developer.clone
assert cloned_developer.name_changed?
assert !cloned_developer.salary_changed? # ... and cloned instance should behave same
end
def test_dup_of_saved_object_marks_attributes_as_dirty
developer = Developer.create! :name => 'Bjorn', :salary => 100000
assert !developer.name_changed?
assert !developer.salary_changed?
cloned_developer = developer.dup
assert cloned_developer.name_changed? # both attributes differ from defaults
assert cloned_developer.salary_changed?
end
def test_dup_of_saved_object_marks_as_dirty_only_changed_attributes
developer = Developer.create! :name => 'Bjorn'
assert !developer.name_changed? # both attributes of saved object should be treated as not changed
assert !developer.salary_changed?
cloned_developer = developer.dup
assert cloned_developer.name_changed? # ... but on cloned object should be
assert !cloned_developer.salary_changed? # ... BUT salary has non-nil default which should be treated as not changed on cloned instance
end
def test_bignum
company = Company.find(1)
company.rating = 2147483647
company.save
company = Company.find(1)
assert_equal 2147483647, company.rating
end
# TODO: extend defaults tests to other databases!
if current_adapter?(:PostgreSQLAdapter)
def test_default
tz = Default.default_timezone
Default.default_timezone = :local
default = Default.new
Default.default_timezone = tz
# fixed dates / times
assert_equal Date.new(2004, 1, 1), default.fixed_date
assert_equal Time.local(2004, 1,1,0,0,0,0), default.fixed_time
# char types
assert_equal 'Y', default.char1
assert_equal 'a varchar field', default.char2
assert_equal 'a text field', default.char3
end
class Geometric < ActiveRecord::Base; end
def test_geometric_content
# accepted format notes:
# ()'s aren't required
# values can be a mix of float or integer
g = Geometric.new(
:a_point => '(5.0, 6.1)',
#:a_line => '((2.0, 3), (5.5, 7.0))' # line type is currently unsupported in postgresql
:a_line_segment => '(2.0, 3), (5.5, 7.0)',
:a_box => '2.0, 3, 5.5, 7.0',
:a_path => '[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]', # [ ] is an open path
:a_polygon => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))',
:a_circle => '<(5.3, 10.4), 2>'
)
assert g.save
# Reload and check that we have all the geometric attributes.
h = Geometric.find(g.id)
assert_equal '(5,6.1)', h.a_point
assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner
assert_equal '[(2,3),(5.5,7),(8.5,11)]', h.a_path
assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
assert_equal '<(5.3,10.4),2>', h.a_circle
# use a geometric function to test for an open path
objs = Geometric.find_by_sql ["select isopen(a_path) from geometrics where id = ?", g.id]
assert_equal true, objs[0].isopen
# test alternate formats when defining the geometric types
g = Geometric.new(
:a_point => '5.0, 6.1',
#:a_line => '((2.0, 3), (5.5, 7.0))' # line type is currently unsupported in postgresql
:a_line_segment => '((2.0, 3), (5.5, 7.0))',
:a_box => '(2.0, 3), (5.5, 7.0)',
:a_path => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))', # ( ) is a closed path
:a_polygon => '2.0, 3, 5.5, 7.0, 8.5, 11.0',
:a_circle => '((5.3, 10.4), 2)'
)
assert g.save
# Reload and check that we have all the geometric attributes.
h = Geometric.find(g.id)
assert_equal '(5,6.1)', h.a_point
assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner
assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_path
assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
assert_equal '<(5.3,10.4),2>', h.a_circle
# use a geometric function to test for an closed path
objs = Geometric.find_by_sql ["select isclosed(a_path) from geometrics where id = ?", g.id]
assert_equal true, objs[0].isclosed
end
end
class NumericData < ActiveRecord::Base
self.table_name = 'numeric_data'
end
def test_big_decimal_conditions
m = NumericData.new(
:bank_balance => 1586.43,
:big_bank_balance => BigDecimal("1000234000567.95"),
:world_population => 6000000000,
:my_house_population => 3
)
assert m.save
assert_equal 0, NumericData.where("bank_balance > ?", 2000.0).count
end
def test_numeric_fields
m = NumericData.new(
:bank_balance => 1586.43,
:big_bank_balance => BigDecimal("1000234000567.95"),
:world_population => 6000000000,
:my_house_population => 3
)
assert m.save
m1 = NumericData.find(m.id)
assert_not_nil m1
# As with migration_test.rb, we should make world_population >= 2**62
# to cover 64-bit platforms and test it is a Bignum, but the main thing
# is that it's an Integer.
assert_kind_of Integer, m1.world_population
assert_equal 6000000000, m1.world_population
assert_kind_of Fixnum, m1.my_house_population
assert_equal 3, m1.my_house_population
assert_kind_of BigDecimal, m1.bank_balance
assert_equal BigDecimal("1586.43"), m1.bank_balance
assert_kind_of BigDecimal, m1.big_bank_balance
assert_equal BigDecimal("1000234000567.95"), m1.big_bank_balance
end
def test_auto_id
auto = AutoId.new
auto.save
assert(auto.id > 0)
end
def test_sql_injection_via_find
assert_raise(ActiveRecord::RecordNotFound, ActiveRecord::StatementInvalid) do
Topic.find("123456 OR id > 0")
end
end
def test_column_name_properly_quoted
col_record = ColumnName.new
col_record.references = 40
assert col_record.save
col_record.references = 41
assert col_record.save
assert_not_nil c2 = ColumnName.find(col_record.id)
assert_equal(41, c2.references)
end
def test_quoting_arrays
replies = Reply.find(:all, :conditions => [ "id IN (?)", topics(:first).replies.collect(&:id) ])
assert_equal topics(:first).replies.size, replies.size
replies = Reply.find(:all, :conditions => [ "id IN (?)", [] ])
assert_equal 0, replies.size
end
MyObject = Struct.new :attribute1, :attribute2
def test_serialized_attribute
Topic.serialize("content", MyObject)
myobj = MyObject.new('value1', 'value2')
topic = Topic.create("content" => myobj)
assert_equal(myobj, topic.content)
topic.reload
assert_equal(myobj, topic.content)
end
def test_serialized_attribute_in_base_class
Topic.serialize("content", Hash)
hash = { 'content1' => 'value1', 'content2' => 'value2' }
important_topic = ImportantTopic.create("content" => hash)
assert_equal(hash, important_topic.content)
important_topic.reload
assert_equal(hash, important_topic.content)
end
# This test was added to fix GH #4004. Obviously the value returned
# is not really the value 'before type cast' so we should maybe think
# about changing that in the future.
def test_serialized_attribute_before_type_cast_returns_unserialized_value
klass = Class.new(ActiveRecord::Base)
klass.table_name = "topics"
klass.serialize :content, Hash
t = klass.new(:content => { :foo => :bar })
assert_equal({ :foo => :bar }, t.content_before_type_cast)
t.save!
t.reload
assert_equal({ :foo => :bar }, t.content_before_type_cast)
end
def test_serialized_attribute_declared_in_subclass
hash = { 'important1' => 'value1', 'important2' => 'value2' }
important_topic = ImportantTopic.create("important" => hash)
assert_equal(hash, important_topic.important)
important_topic.reload
assert_equal(hash, important_topic.important)
assert_equal(hash, important_topic.read_attribute(:important))
end
def test_serialized_time_attribute
myobj = Time.local(2008,1,1,1,0)
topic = Topic.create("content" => myobj).reload
assert_equal(myobj, topic.content)
end
def test_serialized_string_attribute
myobj = "Yes"
topic = Topic.create("content" => myobj).reload
assert_equal(myobj, topic.content)
end
def test_nil_serialized_attribute_without_class_constraint
topic = Topic.new
assert_nil topic.content
end
def test_nil_not_serialized_without_class_constraint
assert Topic.new(:content => nil).save
assert_equal 1, Topic.where(:content => nil).count
end
def test_nil_not_serialized_with_class_constraint
Topic.serialize :content, Hash
assert Topic.new(:content => nil).save
assert_equal 1, Topic.where(:content => nil).count
ensure
Topic.serialize(:content)
end
def test_should_raise_exception_on_serialized_attribute_with_type_mismatch
myobj = MyObject.new('value1', 'value2')
topic = Topic.new(:content => myobj)
assert topic.save
Topic.serialize(:content, Hash)
assert_raise(ActiveRecord::SerializationTypeMismatch) { Topic.find(topic.id).reload.content }
ensure
Topic.serialize(:content)
end
def test_serialized_attribute_with_class_constraint
settings = { "color" => "blue" }
Topic.serialize(:content, Hash)
topic = Topic.new(:content => settings)
assert topic.save
assert_equal(settings, Topic.find(topic.id).content)
ensure
Topic.serialize(:content)
end
def test_serialized_default_class
Topic.serialize(:content, Hash)
topic = Topic.new
assert_equal Hash, topic.content.class
assert_equal Hash, topic.read_attribute(:content).class
topic.content["beer"] = "MadridRb"
assert topic.save
topic.reload
assert_equal Hash, topic.content.class
assert_equal "MadridRb", topic.content["beer"]
ensure
Topic.serialize(:content)
end
def test_serialized_no_default_class_for_object
topic = Topic.new
assert_nil topic.content
end
def test_serialized_boolean_value_true
Topic.serialize(:content)
topic = Topic.new(:content => true)
assert topic.save
topic = topic.reload
assert_equal topic.content, true
end
def test_serialized_boolean_value_false
Topic.serialize(:content)
topic = Topic.new(:content => false)
assert topic.save
topic = topic.reload
assert_equal topic.content, false
end
def test_serialize_with_coder
coder = Class.new {
# Identity
def load(thing)
thing
end
# base 64
def dump(thing)
[thing].pack('m')
end
}.new
Topic.serialize(:content, coder)
s = 'hello world'
topic = Topic.new(:content => s)
assert topic.save
topic = topic.reload
assert_equal [s].pack('m'), topic.content
ensure
Topic.serialize(:content)
end
def test_serialize_with_bcrypt_coder
crypt_coder = Class.new {
def load(thing)
return unless thing
BCrypt::Password.new thing
end
def dump(thing)
BCrypt::Password.create(thing).to_s
end
}.new
Topic.serialize(:content, crypt_coder)
password = 'password'
topic = Topic.new(:content => password)
assert topic.save
topic = topic.reload
assert_kind_of BCrypt::Password, topic.content
assert_equal(true, topic.content == password, 'password should equal')
ensure
Topic.serialize(:content)
end
def test_quote
author_name = "\\ \001 ' \n \\n \""
topic = Topic.create('author_name' => author_name)
assert_equal author_name, Topic.find(topic.id).author_name
end
def test_toggle_attribute
assert !topics(:first).approved?
topics(:first).toggle!(:approved)
assert topics(:first).approved?
topic = topics(:first)
topic.toggle(:approved)
assert !topic.approved?
topic.reload
assert topic.approved?
end
def test_reload
t1 = Topic.find(1)
t2 = Topic.find(1)
t1.title = "something else"
t1.save
t2.reload
assert_equal t1.title, t2.title
end
def test_reload_with_exclusive_scope
dev = DeveloperCalledDavid.first
dev.update_attributes!( :name => "NotDavid" )
assert_equal dev, dev.reload
end
def test_switching_between_table_name
assert_difference("GoodJoke.count") do
Joke.table_name = "cold_jokes"
Joke.create
Joke.table_name = "funny_jokes"
Joke.create
end
end
def test_clear_cash_when_setting_table_name
Joke.table_name = "cold_jokes"
before_columns = Joke.columns
before_seq = Joke.sequence_name
Joke.table_name = "funny_jokes"
after_columns = Joke.columns
after_seq = Joke.sequence_name
assert_not_equal before_columns, after_columns
unless before_seq.nil? && after_seq.nil?
assert_not_equal before_seq, after_seq
assert_equal "cold_jokes_id_seq", before_seq
assert_equal "funny_jokes_id_seq", after_seq
end
end
def test_dont_clear_sequence_name_when_setting_explicitly
Joke.sequence_name = "black_jokes_seq"
Joke.table_name = "cold_jokes"
before_seq = Joke.sequence_name
Joke.table_name = "funny_jokes"
after_seq = Joke.sequence_name
assert_equal before_seq, after_seq unless before_seq.nil? && after_seq.nil?
end
def test_dont_clear_inheritnce_column_when_setting_explicitly
Joke.inheritance_column = "my_type"
before_inherit = Joke.inheritance_column
Joke.reset_column_information
after_inherit = Joke.inheritance_column
assert_equal before_inherit, after_inherit unless before_inherit.blank? && after_inherit.blank?
end
def test_set_table_name_symbol_converted_to_string
Joke.table_name = :cold_jokes
assert_equal 'cold_jokes', Joke.table_name
end
def test_quoted_table_name_after_set_table_name
klass = Class.new(ActiveRecord::Base)
klass.table_name = "foo"
assert_equal "foo", klass.table_name
assert_equal klass.connection.quote_table_name("foo"), klass.quoted_table_name
klass.table_name = "bar"
assert_equal "bar", klass.table_name
assert_equal klass.connection.quote_table_name("bar"), klass.quoted_table_name
end
def test_set_table_name_with_inheritance
k = Class.new( ActiveRecord::Base )
def k.name; "Foo"; end
def k.table_name; super + "ks"; end
assert_equal "foosks", k.table_name
end
def test_sequence_name_with_abstract_class
ak = Class.new(ActiveRecord::Base)
ak.abstract_class = true
k = Class.new(ak)
k.table_name = "projects"
orig_name = k.sequence_name
return skip "sequences not supported by db" unless orig_name
assert_equal k.reset_sequence_name, orig_name
end
def test_count_with_join
res = Post.count_by_sql "SELECT COUNT(*) FROM posts LEFT JOIN comments ON posts.id=comments.post_id WHERE posts.#{QUOTED_TYPE} = 'Post'"
res2 = Post.where("posts.#{QUOTED_TYPE} = 'Post'").joins("LEFT JOIN comments ON posts.id=comments.post_id").count
assert_equal res, res2
res3 = nil
assert_nothing_raised do
res3 = Post.where("posts.#{QUOTED_TYPE} = 'Post'").joins("LEFT JOIN comments ON posts.id=comments.post_id").count
end
assert_equal res, res3
res4 = Post.count_by_sql "SELECT COUNT(p.id) FROM posts p, comments co WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id"
res5 = nil
assert_nothing_raised do
res5 = Post.where("p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id").joins("p, comments co").select("p.id").count
end
assert_equal res4, res5
res6 = Post.count_by_sql "SELECT COUNT(DISTINCT p.id) FROM posts p, comments co WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id"
res7 = nil
assert_nothing_raised do
res7 = Post.where("p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id").joins("p, comments co").select("p.id").count(distinct: true)
end
assert_equal res6, res7
end
def test_no_limit_offset
assert_nothing_raised do
Developer.find(:all, :offset => 2)
end
end
def test_find_last
last = Developer.last
assert_equal last, Developer.find(:first, :order => 'id desc')
end
def test_last
assert_equal Developer.find(:first, :order => 'id desc'), Developer.last
end
def test_all
developers = Developer.all
assert_kind_of Array, developers
assert_equal Developer.all, developers
end
def test_all_with_conditions
assert_equal Developer.find(:all, :order => 'id desc'), Developer.order('id desc').all
end
def test_find_ordered_last
last = Developer.find :last, :order => 'developers.salary ASC'
assert_equal last, Developer.find(:all, :order => 'developers.salary ASC').last
end
def test_find_reverse_ordered_last
last = Developer.find :last, :order => 'developers.salary DESC'
assert_equal last, Developer.find(:all, :order => 'developers.salary DESC').last
end
def test_find_multiple_ordered_last
last = Developer.find :last, :order => 'developers.name, developers.salary DESC'
assert_equal last, Developer.find(:all, :order => 'developers.name, developers.salary DESC').last
end
def test_find_keeps_multiple_order_values
combined = Developer.find(:all, :order => 'developers.name, developers.salary')
assert_equal combined, Developer.find(:all, :order => ['developers.name', 'developers.salary'])
end
def test_find_keeps_multiple_group_values
combined = Developer.find(:all, :group => 'developers.name, developers.salary, developers.id, developers.created_at, developers.updated_at')
assert_equal combined, Developer.find(:all, :group => ['developers.name', 'developers.salary', 'developers.id', 'developers.created_at', 'developers.updated_at'])
end
def test_find_symbol_ordered_last
last = Developer.find :last, :order => :salary
assert_equal last, Developer.find(:all, :order => :salary).last
end
def test_abstract_class
assert !ActiveRecord::Base.abstract_class?
assert LoosePerson.abstract_class?
assert !LooseDescendant.abstract_class?
end
def test_abstract_class_table_name
assert_nil AbstractCompany.table_name
end
def test_base_class
assert_equal LoosePerson, LoosePerson.base_class
assert_equal LooseDescendant, LooseDescendant.base_class
assert_equal TightPerson, TightPerson.base_class
assert_equal TightPerson, TightDescendant.base_class
assert_equal Post, Post.base_class
assert_equal Post, SpecialPost.base_class
assert_equal Post, StiPost.base_class
assert_equal SubStiPost, SubStiPost.base_class
end
def test_descends_from_active_record
assert !ActiveRecord::Base.descends_from_active_record?
# Abstract subclass of AR::Base.
assert LoosePerson.descends_from_active_record?
# Concrete subclass of an abstract class.
assert LooseDescendant.descends_from_active_record?
# Concrete subclass of AR::Base.
assert TightPerson.descends_from_active_record?
# Concrete subclass of a concrete class but has no type column.
assert TightDescendant.descends_from_active_record?
# Concrete subclass of AR::Base.
assert Post.descends_from_active_record?
# Abstract subclass of a concrete class which has a type column.
# This is pathological, as you'll never have Sub < Abstract < Concrete.
assert !StiPost.descends_from_active_record?
# Concrete subclasses an abstract class which has a type column.
assert !SubStiPost.descends_from_active_record?
assert Teapot.descends_from_active_record?
assert !OtherTeapot.descends_from_active_record?
assert CoolTeapot.descends_from_active_record?
end
def test_find_on_abstract_base_class_doesnt_use_type_condition
old_class = LooseDescendant
Object.send :remove_const, :LooseDescendant
descendant = old_class.create! :first_name => 'bob'
assert_not_nil LoosePerson.find(descendant.id), "Should have found instance of LooseDescendant when finding abstract LoosePerson: #{descendant.inspect}"
ensure
unless Object.const_defined?(:LooseDescendant)
Object.const_set :LooseDescendant, old_class
end
end
def test_assert_queries
query = lambda { ActiveRecord::Base.connection.execute 'select count(*) from developers' }
assert_queries(2) { 2.times { query.call } }
assert_queries 1, &query
assert_no_queries { assert true }
end
def test_to_param_should_return_string
assert_kind_of String, Client.first.to_param
end
def test_inspect_class
assert_equal 'ActiveRecord::Base', ActiveRecord::Base.inspect
assert_equal 'LoosePerson(abstract)', LoosePerson.inspect
assert_match(/^Topic\(id: integer, title: string/, Topic.inspect)
end
def test_inspect_instance
topic = topics(:first)
assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@loudthinking.com", written_on: "#{topic.written_on.to_s(:db)}", bonus_time: "#{topic.bonus_time.to_s(:db)}", last_read: "#{topic.last_read.to_s(:db)}", content: "Have a nice day", important: nil, approved: false, replies_count: 1, parent_id: nil, parent_title: nil, type: nil, group: nil, created_at: "#{topic.created_at.to_s(:db)}", updated_at: "#{topic.updated_at.to_s(:db)}">), topic.inspect
end
def test_inspect_new_instance
assert_match(/Topic id: nil/, Topic.new.inspect)
end
def test_inspect_limited_select_instance
assert_equal %(#<Topic id: 1>), Topic.find(:first, :select => 'id', :conditions => 'id = 1').inspect
assert_equal %(#<Topic id: 1, title: "The First Topic">), Topic.find(:first, :select => 'id, title', :conditions => 'id = 1').inspect
end
def test_inspect_class_without_table
assert_equal "NonExistentTable(Table doesn't exist)", NonExistentTable.inspect
end
def test_attribute_for_inspect
t = topics(:first)
t.title = "The First Topic Now Has A Title With\nNewlines And More Than 50 Characters"
assert_equal %("#{t.written_on.to_s(:db)}"), t.attribute_for_inspect(:written_on)
assert_equal '"The First Topic Now Has A Title With\nNewlines And M..."', t.attribute_for_inspect(:title)
end
def test_becomes
assert_kind_of Reply, topics(:first).becomes(Reply)
assert_equal "The First Topic", topics(:first).becomes(Reply).title
end
def test_becomes_includes_errors
company = Company.new(:name => nil)
assert !company.valid?
original_errors = company.errors
client = company.becomes(Client)
assert_equal original_errors, client.errors
end
def test_silence_sets_log_level_to_error_in_block
original_logger = ActiveRecord::Base.logger
log = StringIO.new
ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
ActiveRecord::Base.logger.level = Logger::DEBUG
ActiveRecord::Base.silence do
ActiveRecord::Base.logger.warn "warn"
ActiveRecord::Base.logger.error "error"
end
assert_equal "error\n", log.string
ensure
ActiveRecord::Base.logger = original_logger
end
def test_silence_sets_log_level_back_to_level_before_yield
original_logger = ActiveRecord::Base.logger
log = StringIO.new
ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
ActiveRecord::Base.logger.level = Logger::WARN
ActiveRecord::Base.silence do
end
assert_equal Logger::WARN, ActiveRecord::Base.logger.level
ensure
ActiveRecord::Base.logger = original_logger
end
def test_benchmark_with_log_level
original_logger = ActiveRecord::Base.logger
log = StringIO.new
ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
ActiveRecord::Base.logger.level = Logger::WARN
ActiveRecord::Base.benchmark("Debug Topic Count", :level => :debug) { Topic.count }
ActiveRecord::Base.benchmark("Warn Topic Count", :level => :warn) { Topic.count }
ActiveRecord::Base.benchmark("Error Topic Count", :level => :error) { Topic.count }
assert_no_match(/Debug Topic Count/, log.string)
assert_match(/Warn Topic Count/, log.string)
assert_match(/Error Topic Count/, log.string)
ensure
ActiveRecord::Base.logger = original_logger
end
def test_benchmark_with_use_silence
original_logger = ActiveRecord::Base.logger
log = StringIO.new
ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => false) { ActiveRecord::Base.logger.debug "Quiet" }
assert_match(/Quiet/, log.string)
ensure
ActiveRecord::Base.logger = original_logger
end
def test_compute_type_success
assert_equal Author, ActiveRecord::Base.send(:compute_type, 'Author')
end
def test_compute_type_nonexistent_constant
assert_raises NameError do
ActiveRecord::Base.send :compute_type, 'NonexistentModel'
end
end
def test_compute_type_no_method_error
ActiveSupport::Dependencies.stubs(:constantize).raises(NoMethodError)
assert_raises NoMethodError do
ActiveRecord::Base.send :compute_type, 'InvalidModel'
end
end
def test_compute_type_argument_error
ActiveSupport::Dependencies.stubs(:constantize).raises(ArgumentError)
assert_raises ArgumentError do
ActiveRecord::Base.send :compute_type, 'InvalidModel'
end
end
def test_clear_cache!
# preheat cache
c1 = Post.connection.schema_cache.columns['posts']
ActiveRecord::Base.clear_cache!
c2 = Post.connection.schema_cache.columns['posts']
assert_not_equal c1, c2
end
def test_current_scope_is_reset
Object.const_set :UnloadablePost, Class.new(ActiveRecord::Base)
UnloadablePost.send(:current_scope=, UnloadablePost.scoped)
UnloadablePost.unloadable
assert_not_nil Thread.current[:UnloadablePost_current_scope]
ActiveSupport::Dependencies.remove_unloadable_constants!
assert_nil Thread.current[:UnloadablePost_current_scope]
ensure
Object.class_eval{ remove_const :UnloadablePost } if defined?(UnloadablePost)
end
def test_marshal_round_trip
expected = posts(:welcome)
marshalled = Marshal.dump(expected)
actual = Marshal.load(marshalled)
assert_equal expected.attributes, actual.attributes
end
def test_marshal_new_record_round_trip
marshalled = Marshal.dump(Post.new)
post = Marshal.load(marshalled)
assert post.new_record?, "should be a new record"
end
def test_marshalling_with_associations
post = Post.new
post.comments.build
marshalled = Marshal.dump(post)
post = Marshal.load(marshalled)
assert_equal 1, post.comments.length
end
def test_marshalling_new_record_round_trip_with_associations
post = Post.new
post.comments.build
post = Marshal.load(Marshal.dump(post))
assert post.new_record?, "should be a new record"
end
def test_attribute_names
assert_equal ["id", "type", "ruby_type", "firm_id", "firm_name", "name", "client_of", "rating", "account_id"],
Company.attribute_names
end
def test_attribute_names_on_table_not_exists
assert_equal [], NonExistentTable.attribute_names
end
def test_attribute_names_on_abstract_class
assert_equal [], AbstractCompany.attribute_names
end
def test_cache_key_for_existing_record_is_not_timezone_dependent
ActiveRecord::Base.time_zone_aware_attributes = true
Time.zone = "UTC"
utc_key = Developer.first.cache_key
Time.zone = "EST"
est_key = Developer.first.cache_key
assert_equal utc_key, est_key
ensure
ActiveRecord::Base.time_zone_aware_attributes = false
end
def test_cache_key_format_for_existing_record_with_updated_at
dev = Developer.first
assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:number)}", dev.cache_key
end
def test_cache_key_format_for_existing_record_with_nil_updated_at
dev = Developer.first
dev.update_attribute(:updated_at, nil)
assert_match(/\/#{dev.id}$/, dev.cache_key)
end
def test_uniq_delegates_to_scoped
scope = stub
Bird.stubs(:scoped).returns(mock(:uniq => scope))
assert_equal scope, Bird.uniq
end
def test_active_record_super
assert_equal ActiveRecord::Model, ActiveRecord::Base.active_record_super
assert_equal ActiveRecord::Base, Topic.active_record_super
assert_equal Topic, ImportantTopic.active_record_super
assert_equal ActiveRecord::Model, Teapot.active_record_super
assert_equal Teapot, OtherTeapot.active_record_super
assert_equal ActiveRecord::Model, CoolTeapot.active_record_super
end
def test_table_name_with_2_abstract_subclasses
assert_equal "photos", Photo.table_name
end
def test_column_types_typecast
topic = Topic.first
refute_equal 't.lo', topic.author_name
attrs = topic.attributes.dup
attrs.delete 'id'
typecast = Class.new {
def type_cast value
"t.lo"
end
}
types = { 'author_name' => typecast.new }
topic = Topic.allocate.init_with 'attributes' => attrs,
'column_types' => types
assert_equal 't.lo', topic.author_name
end
def test_typecasting_aliases
assert_equal 10, Topic.select('10 as tenderlove').first.tenderlove
end
def test_slice
company = Company.new(:rating => 1, :name => "37signals", :firm_name => "37signals")
hash = company.slice(:name, :rating, "arbitrary_method")
assert_equal hash[:name], company.name
assert_equal hash['name'], company.name
assert_equal hash[:rating], company.rating
assert_equal hash['arbitrary_method'], company.arbitrary_method
assert_equal hash[:arbitrary_method], company.arbitrary_method
assert_nil hash[:firm_name]
assert_nil hash['firm_name']
end
["find_by", "find_by!"].each do |meth|
test "#{meth} delegates to scoped" do
record = stub
scope = mock
scope.expects(meth).with(:foo, :bar).returns(record)
klass = Class.new(ActiveRecord::Base)
klass.stubs(:scoped => scope)
assert_equal record, klass.public_send(meth, :foo, :bar)
end
end
test "scoped can take a values hash" do
klass = Class.new(ActiveRecord::Base)
assert_equal ['foo'], klass.scoped(select: 'foo').select_values
end
end
|