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
|
# frozen_string_literal: true
require "cases/helper"
require "models/aircraft"
require "models/dashboard"
require "models/clothing_item"
require "models/post"
require "models/comment"
require "models/author"
require "models/topic"
require "models/reply"
require "models/category"
require "models/company"
require "models/developer"
require "models/computer"
require "models/project"
require "models/minimalistic"
require "models/parrot"
require "models/minivan"
require "models/car"
require "models/person"
require "models/ship"
require "models/admin"
require "models/admin/user"
require "models/cpk"
require "models/chat_message"
require "models/default"
require "models/post_with_prefetched_pk"
require "models/pk_autopopulated_by_a_trigger_record"
class PersistenceTest < ActiveRecord::TestCase
fixtures :topics, :companies, :developers, :accounts, :minimalistics, :authors, :author_addresses,
:posts, :minivans, :clothing_items, :cpk_books, :people, :cars
def test_populates_non_primary_key_autoincremented_column
topic = TitlePrimaryKeyTopic.create!(title: "title pk topic")
assert_not_nil topic.attributes["id"]
end
def test_populates_non_primary_key_autoincremented_column_for_a_cpk_model
order = Cpk::Order.create(shop_id: 111_222)
_shop_id, order_id = order.id
assert_not_nil order_id
end
if current_adapter?(:PostgreSQLAdapter)
def test_fills_auto_populated_columns_on_creation
record = Default.create
assert_not_nil record.id
assert_equal "Ruby on Rails", record.ruby_on_rails
if supports_virtual_columns?
assert_not_nil record.virtual_stored_number
end
assert_not_nil record.random_number
assert_not_nil record.modified_date
assert_not_nil record.modified_date_function
assert_not_nil record.modified_time
assert_not_nil record.modified_time_without_precision
assert_not_nil record.modified_time_function
if supports_identity_columns?
klass = Class.new(ActiveRecord::Base) do
self.table_name = "postgresql_identity_table"
end
record = klass.create!
assert_not_nil record.id
end
end
elsif current_adapter?(:SQLite3Adapter)
def test_fills_auto_populated_columns_on_creation
record = Default.create
assert_not_nil record.id
assert_equal "Ruby on Rails", record.ruby_on_rails
assert_not_nil record.random_number
assert_not_nil record.modified_date
assert_not_nil record.modified_date_function
assert_not_nil record.modified_time
assert_not_nil record.modified_time_without_precision
assert_not_nil record.modified_time_function
end
elsif current_adapter?(:Mysql2Adapter, :TrilogyAdapter)
def test_fills_auto_populated_columns_on_creation
record = Default.create
assert_not_nil record.id
assert_not_nil record.char1
if supports_default_expression? && supports_insert_returning?
assert_not_nil record.uuid
end
end
end
def test_update_many
topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } }
updated = Topic.update(topic_data.keys, topic_data.values)
assert_equal [1, 2], updated.map(&:id)
assert_equal "1 updated", Topic.find(1).content
assert_equal "2 updated", Topic.find(2).content
end
def test_update_many_with_duplicated_ids
updated = Topic.update([1, 1, 2], [
{ "content" => "1 duplicated" }, { "content" => "1 updated" }, { "content" => "2 updated" }
])
assert_equal [1, 1, 2], updated.map(&:id)
assert_equal "1 updated", Topic.find(1).content
assert_equal "2 updated", Topic.find(2).content
end
def test_update_many_with_invalid_id
topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" }, 99999 => {} }
assert_raise(ActiveRecord::RecordNotFound) do
Topic.update(topic_data.keys, topic_data.values)
end
assert_not_equal "1 updated", Topic.find(1).content
assert_not_equal "2 updated", Topic.find(2).content
end
def test_update_many_with_active_record_base_object
error = assert_raises(ArgumentError) do
Topic.update(Topic.first, "content" => "1 updated")
end
assert_equal "You are passing an instance of ActiveRecord::Base to `update`. " \
"Please pass the id of the object by calling `.id`.", error.message
assert_not_equal "1 updated", Topic.first.content
end
def test_update_many_with_array_of_active_record_base_objects
error = assert_raise(ArgumentError) do
Topic.update(Topic.first(2), content: "updated")
end
assert_equal "You are passing an array of ActiveRecord::Base instances to `update`. " \
"Please pass the ids of the objects by calling `pluck(:id)` or `map(&:id)`.", error.message
assert_not_equal "updated", Topic.first.content
assert_not_equal "updated", Topic.second.content
end
def test_class_level_update_without_ids
topics = Topic.all
assert_equal 5, topics.length
topics.each do |topic|
assert_not_equal "updated", topic.content
end
updated = Topic.update(content: "updated")
assert_equal 5, updated.length
updated.each do |topic|
assert_equal "updated", topic.content
end
end
def test_class_level_update_is_affected_by_scoping
topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } }
assert_raise(ActiveRecord::RecordNotFound) do
Topic.where("1=0").scoping { Topic.update(topic_data.keys, topic_data.values) }
end
assert_not_equal "1 updated", Topic.find(1).content
assert_not_equal "2 updated", Topic.find(2).content
end
def test_returns_object_even_if_validations_failed
assert_equal Developer.all.to_a, Developer.update(salary: 1_000_000)
end
def test_update_many!
topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } }
updated = Topic.update!(topic_data.keys, topic_data.values)
assert_equal [1, 2], updated.map(&:id)
assert_equal "1 updated", Topic.find(1).content
assert_equal "2 updated", Topic.find(2).content
end
def test_update_many_with_duplicated_ids!
updated = Topic.update!([1, 1, 2], [
{ "content" => "1 duplicated" }, { "content" => "1 updated" }, { "content" => "2 updated" }
])
assert_equal [1, 1, 2], updated.map(&:id)
assert_equal "1 updated", Topic.find(1).content
assert_equal "2 updated", Topic.find(2).content
end
def test_update_many_with_invalid_id!
topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" }, 99999 => {} }
assert_raise(ActiveRecord::RecordNotFound) do
Topic.update!(topic_data.keys, topic_data.values)
end
assert_not_equal "1 updated", Topic.find(1).content
assert_not_equal "2 updated", Topic.find(2).content
end
def test_update_many_with_active_record_base_object!
error = assert_raises(ArgumentError) do
Topic.update!(Topic.first, "content" => "1 updated")
end
assert_equal "You are passing an instance of ActiveRecord::Base to `update!`. " \
"Please pass the id of the object by calling `.id`.", error.message
assert_not_equal "1 updated", Topic.first.content
end
def test_update_many_with_array_of_active_record_base_objects!
error = assert_raise(ArgumentError) do
Topic.update!(Topic.first(2), content: "updated")
end
assert_equal "You are passing an array of ActiveRecord::Base instances to `update!`. " \
"Please pass the ids of the objects by calling `pluck(:id)` or `map(&:id)`.", error.message
assert_not_equal "updated", Topic.first.content
assert_not_equal "updated", Topic.second.content
end
def test_class_level_update_without_ids!
topics = Topic.all
assert_equal 5, topics.length
topics.each do |topic|
assert_not_equal "updated", topic.content
end
updated = Topic.update!(content: "updated")
assert_equal 5, updated.length
updated.each do |topic|
assert_equal "updated", topic.content
end
end
def test_class_level_update_is_affected_by_scoping!
topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } }
assert_raise(ActiveRecord::RecordNotFound) do
Topic.where("1=0").scoping { Topic.update!(topic_data.keys, topic_data.values) }
end
assert_not_equal "1 updated", Topic.find(1).content
assert_not_equal "2 updated", Topic.find(2).content
end
def test_raises_error_when_validations_failed
assert_raises(ActiveRecord::RecordInvalid) do
Developer.update!(salary: 1_000_000)
end
end
def test_delete_all
assert Topic.count > 0
assert_equal Topic.count, Topic.delete_all
end
def test_increment_attribute
assert_equal 50, accounts(:signals37).credit_limit
accounts(:signals37).increment! :credit_limit
assert_equal 51, accounts(:signals37, :reload).credit_limit
accounts(:signals37).increment(:credit_limit).increment!(:credit_limit)
assert_equal 53, accounts(:signals37, :reload).credit_limit
end
def test_increment_aliased_attribute
assert_equal 50, accounts(:signals37).available_credit
accounts(:signals37).increment!(:available_credit)
assert_equal 51, accounts(:signals37, :reload).available_credit
accounts(:signals37).increment(:available_credit).increment!(:available_credit)
assert_equal 53, accounts(:signals37, :reload).available_credit
end
def test_increment_nil_attribute
assert_nil topics(:first).parent_id
topics(:first).increment! :parent_id
assert_equal 1, topics(:first).parent_id
end
def test_increment_attribute_by
assert_equal 50, accounts(:signals37).credit_limit
accounts(:signals37).increment! :credit_limit, 5
assert_equal 55, accounts(:signals37, :reload).credit_limit
accounts(:signals37).increment(:credit_limit, 1).increment!(:credit_limit, 3)
assert_equal 59, accounts(:signals37, :reload).credit_limit
end
def test_increment_updates_counter_in_db_using_offset
a1 = accounts(:signals37)
initial_credit = a1.credit_limit
a2 = Account.find(accounts(:signals37).id)
a1.increment!(:credit_limit)
a2.increment!(:credit_limit)
assert_equal initial_credit + 2, a1.reload.credit_limit
end
def test_increment_with_touch_updates_timestamps
topic = topics(:first)
assert_equal 1, topic.replies_count
previously_updated_at = topic.updated_at
travel(1.second) do
topic.increment!(:replies_count, touch: true)
end
assert_equal 2, topic.reload.replies_count
assert_operator previously_updated_at, :<, topic.updated_at
end
def test_increment_with_touch_an_attribute_updates_timestamps
topic = topics(:first)
assert_equal 1, topic.replies_count
previously_updated_at = topic.updated_at
previously_written_on = topic.written_on
travel(1.second) do
topic.increment!(:replies_count, touch: :written_on)
end
assert_equal 2, topic.reload.replies_count
assert_operator previously_updated_at, :<, topic.updated_at
assert_operator previously_written_on, :<, topic.written_on
end
def test_increment_with_no_arg
topic = topics(:first)
assert_raises(ArgumentError) { topic.increment! }
end
def test_destroy_many
clients = Client.find([2, 3])
assert_difference("Client.count", -2) do
destroyed = Client.destroy([2, 3])
assert_equal clients, destroyed
assert destroyed.all?(&:frozen?), "destroyed clients should be frozen"
end
end
def test_destroy_many_with_invalid_id
clients = Client.find([2, 3])
assert_raise(ActiveRecord::RecordNotFound) do
Client.destroy([2, 3, 99999])
end
assert_equal clients, Client.find([2, 3])
end
def test_destroy_with_single_composite_primary_key
book = cpk_books(:cpk_great_author_first_book)
assert_difference("Cpk::Book.count", -1) do
destroyed = Cpk::Book.destroy(book.id)
assert_equal destroyed, book
end
end
def test_destroy_with_multiple_composite_primary_keys
books = [
cpk_books(:cpk_great_author_first_book),
cpk_books(:cpk_great_author_second_book),
]
assert_difference("Cpk::Book.count", -2) do
destroyed = Cpk::Book.destroy(books.map(&:id))
assert_equal books.sort, destroyed.sort
assert destroyed.all?(&:frozen?), "destroyed clients should be frozen"
end
end
def test_destroy_with_invalid_ids_for_a_model_that_expects_composite_keys
books = [
cpk_books(:cpk_great_author_first_book),
cpk_books(:cpk_great_author_second_book),
]
assert_raise(ActiveRecord::RecordNotFound) do
ids = books.map { |book| book.id.first }
Cpk::Book.destroy(ids)
end
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_after_reload_schema_from_cache
Reply.define_attribute_methods
Reply.serialize(:content) # invoke reload_schema_from_cache
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_not_predicate company, :valid?
original_errors = company.errors
client = company.becomes(Client)
assert_equal original_errors.attribute_names, client.errors.attribute_names
end
def test_becomes_errors_base
child_class = Class.new(Admin::User) do
store_accessor :settings, :foo
def self.name; "Admin::ChildUser"; end
end
admin = Admin::User.new
admin.errors.add :token, :invalid
child = admin.becomes(child_class)
assert_equal [:token], child.errors.attribute_names
assert_nothing_raised do
child.errors.add :foo, :invalid
end
end
def test_duped_becomes_persists_changes_from_the_original
original = topics(:first)
copy = original.dup.becomes(Reply)
copy.save!
assert_equal "The First Topic", Topic.find(copy.id).title
end
def test_becomes_wont_break_mutation_tracking
topic = topics(:first)
reply = topic.becomes(Reply)
assert_equal 1, topic.id_in_database
assert_empty topic.attributes_in_database
assert_equal 1, reply.id_in_database
assert_empty reply.attributes_in_database
end
def test_becomes_includes_changed_attributes
company = Company.new(name: "37signals")
client = company.becomes(Client)
assert_equal "37signals", client.name
assert_equal %w{name}, client.changed
end
def test_becomes_initializes_missing_attributes
company = Company.new(name: "GrowingCompany")
client = company.becomes(LargeClient)
assert_equal 50, client.extra_size
end
def test_becomes_keeps_extra_attributes
client = LargeClient.new(name: "ShrinkingCompany")
company = client.becomes(Company)
assert_equal 50, company.extra_size
assert_equal 50, client.extra_size
end
def test_delete_many
original_count = Topic.count
Topic.delete(deleting = [1, 2])
assert_equal original_count - deleting.size, Topic.count
end
def test_decrement_attribute
assert_equal 50, accounts(:signals37).credit_limit
accounts(:signals37).decrement!(:credit_limit)
assert_equal 49, accounts(:signals37, :reload).credit_limit
accounts(:signals37).decrement(:credit_limit).decrement!(:credit_limit)
assert_equal 47, accounts(:signals37, :reload).credit_limit
end
def test_decrement_attribute_by
assert_equal 50, accounts(:signals37).credit_limit
accounts(:signals37).decrement! :credit_limit, 5
assert_equal 45, accounts(:signals37, :reload).credit_limit
accounts(:signals37).decrement(:credit_limit, 1).decrement!(:credit_limit, 3)
assert_equal 41, accounts(:signals37, :reload).credit_limit
end
def test_decrement_with_touch_updates_timestamps
topic = topics(:first)
assert_equal 1, topic.replies_count
previously_updated_at = topic.updated_at
travel(1.second) do
topic.decrement!(:replies_count, touch: true)
end
assert_equal 0, topic.reload.replies_count
assert_operator previously_updated_at, :<, topic.updated_at
end
def test_decrement_with_touch_an_attribute_updates_timestamps
topic = topics(:first)
assert_equal 1, topic.replies_count
previously_updated_at = topic.updated_at
previously_written_on = topic.written_on
travel(1.second) do
topic.decrement!(:replies_count, touch: :written_on)
end
assert_equal 0, topic.reload.replies_count
assert_operator previously_updated_at, :<, topic.updated_at
assert_operator previously_written_on, :<, topic.written_on
end
def test_create
topic = Topic.new
topic.title = "New Topic"
topic.save
topic_reloaded = Topic.find(topic.id)
assert_equal("New Topic", topic_reloaded.title)
end
def test_create_prefetched_pk
post = PostWithPrefetchedPk.create!(title: "New Message", body: "New Body")
assert_equal 123456, post.id
end
def test_create_model_with_uuid_pk_populates_id
message = ChatMessage.create(content: "New Message")
assert_not_nil message.id
message_reloaded = ChatMessage.find(message.id)
assert_equal "New Message", message_reloaded.content
end if current_adapter?(:PostgreSQLAdapter)
def test_create_model_with_custom_named_uuid_pk_populates_id
message = ChatMessageCustomPk.create(content: "New Message")
assert_not_nil message.message_id
message_reloaded = ChatMessageCustomPk.find(message.message_id)
assert_equal "New Message", message_reloaded.content
end if current_adapter?(:PostgreSQLAdapter)
def test_build
topic = Topic.build(title: "New Topic")
assert_equal "New Topic", topic.title
assert_not_predicate topic, :persisted?
end
def test_build_many
topics = Topic.build([{ title: "first" }, { title: "second" }])
assert_equal ["first", "second"], topics.map(&:title)
topics.each { |topic| assert_not_predicate topic, :persisted? }
end
def test_build_through_factory_with_block
topic = Topic.build("title" => "New Topic") do |t|
t.author_name = "David"
end
assert_equal("New Topic", topic.title)
assert_equal("David", topic.author_name)
assert_not_predicate topic, :persisted?
end
def test_build_many_through_factory_with_block
topics = Topic.build([{ "title" => "first" }, { "title" => "second" }]) do |t|
t.author_name = "David"
end
assert_equal 2, topics.size
topics.each { |topic| assert_not_predicate topic, :persisted? }
topic1, topic2 = topics
assert_equal "first", topic1.title
assert_equal "David", topic1.author_name
assert_equal "second", topic2.title
assert_equal "David", topic2.author_name
end
def test_save_valid_record
topic = Topic.new(title: "New Topic")
assert topic.save!
end
def test_save_invalid_record
reply = WrongReply.new(title: "New reply")
error = assert_raise(ActiveRecord::RecordInvalid) { reply.save! }
assert_equal "Validation failed: Content Empty", error.message
end
def test_save_destroyed_object
topic = Topic.create!(title: "New Topic")
topic.destroy!
error = assert_raise(ActiveRecord::RecordNotSaved) { topic.save! }
assert_equal "Failed to save the record", error.message
end
def test_save_null_string_attributes
topic = Topic.find(1)
topic.attributes = { "title" => "null", "author_name" => "null" }
topic.save!
topic.reload
assert_equal("null", topic.title)
assert_equal("null", topic.author_name)
end
def test_save_nil_string_attributes
topic = Topic.find(1)
topic.title = nil
topic.save!
topic.reload
assert_nil topic.title
end
def test_save_for_record_with_only_primary_key
minimalistic = Minimalistic.new
assert_nothing_raised { minimalistic.save }
end
def test_save_for_record_with_only_primary_key_that_is_provided
assert_nothing_raised { Minimalistic.create!(id: 2) }
end
def test_save_with_duping_of_destroyed_object
developer = Developer.first
developer.destroy
new_developer = developer.dup
new_developer.save
assert_predicate new_developer, :persisted?
assert_not_predicate new_developer, :destroyed?
end
def test_create_many
topics = Topic.create([ { "title" => "first" }, { "title" => "second" }])
assert_equal 2, topics.size
assert_equal "first", topics.first.title
end
def test_create_columns_not_equal_attributes
topic = Topic.instantiate(
"title" => "Another New Topic",
"does_not_exist" => "test"
)
topic = topic.dup # reset @new_record
assert_nothing_raised { topic.save }
assert_predicate topic, :persisted?
assert_equal "Another New Topic", topic.reload.title
end
def test_create_through_factory_with_block
topic = Topic.create("title" => "New Topic") do |t|
t.author_name = "David"
end
assert_equal("New Topic", topic.title)
assert_equal("David", topic.author_name)
end
def test_create_many_through_factory_with_block
topics = Topic.create([ { "title" => "first" }, { "title" => "second" }]) do |t|
t.author_name = "David"
end
assert_equal 2, topics.size
topic1, topic2 = Topic.find(topics[0].id), Topic.find(topics[1].id)
assert_equal "first", topic1.title
assert_equal "David", topic1.author_name
assert_equal "second", topic2.title
assert_equal "David", topic2.author_name
end
def test_update_object
topic = Topic.new
topic.title = "Another New Topic"
topic.written_on = "2003-12-12 23:23:00"
topic.save
topic_reloaded = Topic.find(topic.id)
assert_equal("Another New Topic", topic_reloaded.title)
topic_reloaded.title = "Updated topic"
topic_reloaded.save
topic_reloaded_again = Topic.find(topic.id)
assert_equal("Updated topic", topic_reloaded_again.title)
end
def test_update_columns_not_equal_attributes
topic = Topic.new
topic.title = "Still another topic"
topic.save
topic_reloaded = Topic.instantiate(topic.attributes.merge("does_not_exist" => "test"))
topic_reloaded.title = "A New Topic"
assert_nothing_raised { topic_reloaded.save }
assert_predicate topic_reloaded, :persisted?
assert_equal "A New Topic", topic_reloaded.reload.title
end
def test_update_for_record_with_only_primary_key
minimalistic = minimalistics(:first)
assert_nothing_raised { minimalistic.save }
end
def test_update_sti_type
assert_instance_of Reply, topics(:second)
topic = topics(:second).becomes!(Topic)
assert_instance_of Topic, topic
topic.save!
assert_instance_of Topic, Topic.find(topic.id)
end
def test_preserve_original_sti_type
reply = topics(:second)
assert_equal "Reply", reply.type
topic = reply.becomes(Topic)
assert_equal "Reply", reply.type
assert_instance_of Topic, topic
assert_equal "Reply", topic.type
end
def test_update_sti_subclass_type
assert_instance_of Topic, topics(:first)
reply = topics(:first).becomes!(Reply)
assert_instance_of Reply, reply
reply.save!
assert_instance_of Reply, Reply.find(reply.id)
end
def test_becomes_default_sti_subclass
original_type = Topic.columns_hash["type"].default
ActiveRecord::Base.lease_connection.change_column_default :topics, :type, "Reply"
Topic.reset_column_information
reply = topics(:second)
assert_instance_of Reply, reply
topic = reply.becomes(Topic)
assert_instance_of Topic, topic
ensure
ActiveRecord::Base.lease_connection.change_column_default :topics, :type, original_type
Topic.reset_column_information
end
def test_update_after_create
klass = Class.new(Topic) do
def self.name; "Topic"; end
after_create do
update_attribute("author_name", "David")
end
end
topic = klass.new
topic.title = "Another New Topic"
topic.save
topic_reloaded = Topic.find(topic.id)
assert_equal("Another New Topic", topic_reloaded.title)
assert_equal("David", topic_reloaded.author_name)
end
def test_update_attribute_after_update
klass = Class.new(Topic) do
def self.name; "Topic"; end
after_update :update_author, if: :saved_change_to_title?
def update_author
update_attribute("author_name", "David")
end
end
topic = klass.create(title: "New Topic")
topic.update(title: "Another Topic")
topic_reloaded = Topic.find(topic.id)
assert_equal("Another Topic", topic_reloaded.title)
assert_equal("David", topic_reloaded.author_name)
end
def test_update_attribute_in_before_validation_respects_callback_chain
klass = Class.new(Topic) do
def self.name; "Topic"; end
before_validation :set_author_name
after_create :track_create
after_update :call_once, if: :saved_change_to_author_name?
attr_reader :counter
def set_author_name
update_attribute :author_name, "David"
end
def track_create
call_once if saved_change_to_author_name?
end
def call_once
@counter ||= 0
@counter += 1
end
end
comment = klass.create(title: "New Topic", author_name: "Not David")
assert_equal 1, comment.counter
end
def test_update_attribute_does_not_run_sql_if_attribute_is_not_changed
topic = Topic.create(title: "Another New Topic")
assert_no_queries do
assert topic.update_attribute(:title, "Another New Topic")
end
end
def test_update_does_not_run_sql_if_record_has_not_changed
topic = Topic.create(title: "Another New Topic")
assert_no_queries do
assert topic.update(title: "Another New Topic")
end
end
def test_delete
topic = Topic.find(1)
assert_equal topic, topic.delete, "topic.delete did not return self"
assert_predicate topic, :frozen?, "topic not frozen after delete"
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
end
def test_delete_doesnt_run_callbacks
Topic.find(1).delete
assert_not_nil Topic.find(2)
end
def test_delete_isnt_affected_by_scoping
topic = Topic.find(1)
assert_difference("Topic.count", -1) do
Topic.where("1=0").scoping { topic.delete }
end
end
def test_destroy
topic = Topic.find(1)
assert_equal topic, topic.destroy, "topic.destroy did not return self"
assert_predicate topic, :frozen?, "topic not frozen after destroy"
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
end
def test_destroy!
topic = Topic.find(1)
assert_equal topic, topic.destroy!, "topic.destroy! did not return self"
assert_predicate topic, :frozen?, "topic not frozen after destroy!"
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
end
def test_destroy_for_a_failed_to_destroy_cpk_record
book = cpk_books(:cpk_great_author_first_book)
book.fail_destroy = true
assert_raises(ActiveRecord::RecordNotDestroyed, match: /Failed to destroy Cpk::Book with \["author_id", "id"\]=/) do
book.destroy!
end
end
def test_find_raises_record_not_found_exception
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(99999) }
end
def test_update_raises_record_not_found_exception
assert_raise(ActiveRecord::RecordNotFound) { Topic.update(99999, approved: true) }
end
def test_destroy_raises_record_not_found_exception
assert_raise(ActiveRecord::RecordNotFound) { Topic.destroy(99999) }
end
def test_update_all
assert_equal Topic.count, Topic.update_all("content = 'bulk updated!'")
assert_equal "bulk updated!", Topic.find(1).content
assert_equal "bulk updated!", Topic.find(2).content
assert_equal Topic.count, Topic.update_all(["content = ?", "bulk updated again!"])
assert_equal "bulk updated again!", Topic.find(1).content
assert_equal "bulk updated again!", Topic.find(2).content
assert_equal Topic.count, Topic.update_all(["content = ?", nil])
assert_nil Topic.find(1).content
end
def test_update_all_with_hash
assert_not_nil Topic.find(1).last_read
assert_equal Topic.count, Topic.update_all(content: "bulk updated with hash!", last_read: nil)
assert_equal "bulk updated with hash!", Topic.find(1).content
assert_equal "bulk updated with hash!", Topic.find(2).content
assert_nil Topic.find(1).last_read
assert_nil Topic.find(2).last_read
end
def test_update_all_with_custom_sql_as_value
person = people(:michael)
person.update!(cars_count: 0)
Person.update_all(cars_count: Arel.sql(<<~SQL))
select count(*) from cars where cars.person_id = people.id
SQL
assert_equal 1, person.reload.cars_count
end
def test_delete_new_record
client = Client.new(name: "37signals")
client.delete
assert_predicate client, :frozen?
assert_not client.save
assert_raise(ActiveRecord::RecordNotSaved) { client.save! }
assert_predicate client, :frozen?
assert_raise(RuntimeError) { client.name = "something else" }
end
def test_delete_record_with_associations
client = Client.find(3)
client.delete
assert_predicate client, :frozen?
assert_kind_of Firm, client.firm
assert_not client.save
assert_raise(ActiveRecord::RecordNotSaved) { client.save! }
assert_predicate client, :frozen?
assert_raise(RuntimeError) { client.name = "something else" }
end
def test_destroy_new_record
client = Client.new(name: "37signals")
client.destroy
assert_predicate client, :frozen?
assert_not client.save
assert_raise(ActiveRecord::RecordNotSaved) { client.save! }
assert_predicate client, :frozen?
assert_raise(RuntimeError) { client.name = "something else" }
end
def test_destroy_record_with_associations
client = Client.find(3)
client.destroy
assert_predicate client, :frozen?
assert_kind_of Firm, client.firm
assert_not client.save
assert_raise(ActiveRecord::RecordNotSaved) { client.save! }
assert_predicate client, :frozen?
assert_raise(RuntimeError) { client.name = "something else" }
end
def test_update_attribute
assert_not_predicate Topic.find(1), :approved?
Topic.find(1).update_attribute("approved", true)
assert_predicate Topic.find(1), :approved?
Topic.find(1).update_attribute(:approved, false)
assert_not_predicate Topic.find(1), :approved?
Topic.find(1).update_attribute(:change_approved_before_save, true)
assert_predicate Topic.find(1), :approved?
end
def test_update_attribute_for_readonly_attribute
minivan = Minivan.find("m1")
assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_attribute(:color, "black") }
end
def test_update_attribute_with_one_updated
t = Topic.first
t.update_attribute(:title, "super_title")
assert_equal "super_title", t.title
assert_not t.changed?, "topic should not have changed"
assert_not t.title_changed?, "title should not have changed"
assert_nil t.title_change, "title change should be nil"
t.reload
assert_equal "super_title", t.title
end
def test_update_attribute_for_updated_at_on
developer = Developer.find(1)
prev_month = Time.now.prev_month.change(usec: 0)
developer.update_attribute(:updated_at, prev_month)
assert_equal prev_month, developer.updated_at
developer.update_attribute(:salary, 80001)
assert_not_equal prev_month, developer.updated_at
developer.reload
assert_not_equal prev_month, developer.updated_at
end
def test_update_attribute!
assert_not_predicate Topic.find(1), :approved?
Topic.find(1).update_attribute!("approved", true)
assert_predicate Topic.find(1), :approved?
Topic.find(1).update_attribute!(:approved, false)
assert_not_predicate Topic.find(1), :approved?
Topic.find(1).update_attribute!(:change_approved_before_save, true)
assert_predicate Topic.find(1), :approved?
end
def test_update_attribute_for_readonly_attribute!
minivan = Minivan.find("m1")
assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_attribute!(:color, "black") }
end
def test_update_attribute_with_one_updated!
t = Topic.first
t.update_attribute!(:title, "super_title")
assert_equal "super_title", t.title
assert_not t.changed?, "topic should not have changed"
assert_not t.title_changed?, "title should not have changed"
assert_nil t.title_change, "title change should be nil"
t.reload
assert_equal "super_title", t.title
end
def test_update_attribute_for_updated_at_on!
developer = Developer.find(1)
prev_month = Time.now.prev_month.change(usec: 0)
developer.update_attribute!(:updated_at, prev_month)
assert_equal prev_month, developer.updated_at
developer.update_attribute!(:salary, 80001)
assert_not_equal prev_month, developer.updated_at
developer.reload
assert_not_equal prev_month, developer.updated_at
end
def test_update_attribute_for_aborted_callback!
klass = Class.new(Topic) do
def self.name; "Topic"; end
before_update :throw_abort
def throw_abort
throw(:abort)
end
end
t = klass.create(title: "New Topic", author_name: "Not David")
assert_raises(ActiveRecord::RecordNotSaved) { t.update_attribute!(:title, "super_title") }
t_reloaded = Topic.find(t.id)
assert_equal "New Topic", t_reloaded.title
end
def test_update_column
topic = Topic.find(1)
topic.update_column("approved", true)
assert_predicate topic, :approved?
topic.reload
assert_predicate topic, :approved?
topic.update_column(:approved, false)
assert_not_predicate topic, :approved?
topic.reload
assert_not_predicate topic, :approved?
end
def test_update_column_should_not_use_setter_method
dev = Developer.find(1)
dev.instance_eval { def salary=(value); write_attribute(:salary, value * 2); end }
dev.update_column(:salary, 80000)
assert_equal 80000, dev.salary
dev.reload
assert_equal 80000, dev.salary
end
def test_update_column_should_raise_exception_if_new_record
topic = Topic.new
assert_raises(ActiveRecord::ActiveRecordError) { topic.update_column("approved", false) }
end
def test_update_column_should_not_leave_the_object_dirty
topic = Topic.find(1)
topic.update_column("content", "--- Have a nice day\n...\n")
topic.reload
topic.update_column(:content, "--- You too\n...\n")
assert_equal [], topic.changed
topic.reload
topic.update_column("content", "--- Have a nice day\n...\n")
assert_equal [], topic.changed
end
def test_update_column_with_model_having_primary_key_other_than_id
minivan = Minivan.find("m1")
new_name = "sebavan"
minivan.update_column(:name, new_name)
assert_equal new_name, minivan.name
end
def test_update_column_for_readonly_attribute
minivan = Minivan.find("m1")
prev_color = minivan.color
assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_column(:color, "black") }
assert_equal prev_color, minivan.color
end
def test_update_column_should_not_modify_updated_at
developer = Developer.find(1)
prev_month = Time.now.prev_month.change(usec: 0)
developer.update_column(:updated_at, prev_month)
assert_equal prev_month, developer.updated_at
developer.update_column(:salary, 80001)
assert_equal prev_month, developer.updated_at
developer.reload
assert_equal prev_month.to_i, developer.updated_at.to_i
end
def test_update_column_with_one_changed_and_one_updated
t = Topic.order("id").limit(1).first
author_name = t.author_name
t.author_name = "John"
t.update_column(:title, "super_title")
assert_equal "John", t.author_name
assert_equal "super_title", t.title
assert_predicate t, :changed?, "topic should have changed"
assert_predicate t, :author_name_changed?, "author_name should have changed"
t.reload
assert_equal author_name, t.author_name
assert_equal "super_title", t.title
end
def test_update_column_with_default_scope
developer = DeveloperCalledDavid.first
developer.name = "John"
developer.save!
assert developer.update_column(:name, "Will"), "did not update record due to default scope"
end
def test_update_columns
topic = Topic.find(1)
topic.update_columns("approved" => true, title: "Sebastian Topic")
assert_predicate topic, :approved?
assert_equal "Sebastian Topic", topic.title
topic.reload
assert_predicate topic, :approved?
assert_equal "Sebastian Topic", topic.title
end
def test_update_columns_should_not_use_setter_method
dev = Developer.find(1)
dev.instance_eval { def salary=(value); write_attribute(:salary, value * 2); end }
dev.update_columns(salary: 80000)
assert_equal 80000, dev.salary
dev.reload
assert_equal 80000, dev.salary
end
def test_update_columns_should_raise_exception_if_new_record
topic = Topic.new
assert_raises(ActiveRecord::ActiveRecordError) { topic.update_columns(approved: false) }
end
def test_update_columns_should_not_leave_the_object_dirty
topic = Topic.find(1)
topic.update("content" => "--- Have a nice day\n...\n", :author_name => "Jose")
topic.reload
topic.update_columns(content: "--- You too\n...\n", "author_name" => "Sebastian")
assert_equal [], topic.changed
topic.reload
topic.update_columns(content: "--- Have a nice day\n...\n", author_name: "Jose")
assert_equal [], topic.changed
end
def test_update_columns_with_model_having_primary_key_other_than_id
minivan = Minivan.find("m1")
new_name = "sebavan"
minivan.update_columns(name: new_name)
assert_equal new_name, minivan.name
end
def test_update_columns_with_one_readonly_attribute
minivan = Minivan.find("m1")
prev_color = minivan.color
prev_name = minivan.name
assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_columns(name: "My old minivan", color: "black") }
assert_equal prev_color, minivan.color
assert_equal prev_name, minivan.name
minivan.reload
assert_equal prev_color, minivan.color
assert_equal prev_name, minivan.name
end
def test_update_columns_should_not_modify_updated_at
developer = Developer.find(1)
prev_month = Time.now.prev_month.change(usec: 0)
developer.update_columns(updated_at: prev_month)
assert_equal prev_month, developer.updated_at
developer.update_columns(salary: 80000)
assert_equal prev_month, developer.updated_at
assert_equal 80000, developer.salary
developer.reload
assert_equal prev_month.to_i, developer.updated_at.to_i
assert_equal 80000, developer.salary
end
def test_update_columns_with_one_changed_and_one_updated
t = Topic.order("id").limit(1).first
author_name = t.author_name
t.author_name = "John"
t.update_columns(title: "super_title")
assert_equal "John", t.author_name
assert_equal "super_title", t.title
assert_predicate t, :changed?, "topic should have changed"
assert_predicate t, :author_name_changed?, "author_name should have changed"
t.reload
assert_equal author_name, t.author_name
assert_equal "super_title", t.title
end
def test_update_columns_changing_id
topic = Topic.find(1)
topic.update_columns(id: 123)
assert_equal 123, topic.id
topic.reload
assert_equal 123, topic.id
end
def test_update_columns_returns_boolean
topic = Topic.find(1)
assert_equal true, topic.update_columns(title: "New title")
end
def test_update_columns_with_default_scope
developer = DeveloperCalledDavid.first
developer.name = "John"
developer.save!
assert developer.update_columns(name: "Will"), "did not update record due to default scope"
end
def test_update
topic = Topic.find(1)
assert_not_predicate topic, :approved?
assert_equal "The First Topic", topic.title
topic.update("approved" => true, "title" => "The First Topic Updated")
topic.reload
assert_predicate topic, :approved?
assert_equal "The First Topic Updated", topic.title
topic.update(approved: false, title: "The First Topic")
topic.reload
assert_not_predicate topic, :approved?
assert_equal "The First Topic", topic.title
error = assert_raise(ActiveRecord::RecordNotUnique, ActiveRecord::StatementInvalid) do
topic.update(id: 3, title: "Hm is it possible?")
end
assert_not_nil error.cause
assert_not_equal "Hm is it possible?", Topic.find(3).title
topic.update(id: 1234)
assert_nothing_raised { topic.reload }
assert_equal topic.title, Topic.find(1234).title
end
def test_update_parameters
topic = Topic.find(1)
assert_nothing_raised do
topic.update({})
end
assert_raises(ArgumentError) do
topic.update(nil)
end
end
def test_update!
Reply.validates_presence_of(:title)
reply = Reply.find(2)
assert_equal "The Second Topic of the day", reply.title
assert_equal "Have a nice day", reply.content
reply.update!("title" => "The Second Topic of the day updated", "content" => "Have a nice evening")
reply.reload
assert_equal "The Second Topic of the day updated", reply.title
assert_equal "Have a nice evening", reply.content
reply.update!(title: "The Second Topic of the day", content: "Have a nice day")
reply.reload
assert_equal "The Second Topic of the day", reply.title
assert_equal "Have a nice day", reply.content
assert_raise(ActiveRecord::RecordInvalid) { reply.update!(title: nil, content: "Have a nice evening") }
ensure
Reply.clear_validators!
end
def test_destroyed_returns_boolean
developer = Developer.first
assert_equal false, developer.destroyed?
developer.destroy
assert_equal true, developer.destroyed?
developer = Developer.last
assert_equal false, developer.destroyed?
developer.delete
assert_equal true, developer.destroyed?
end
def test_persisted_returns_boolean
developer = Developer.new(name: "Jose")
assert_equal false, developer.persisted?
developer.save!
assert_equal true, developer.persisted?
developer = Developer.first
assert_equal true, developer.persisted?
developer.destroy
assert_equal false, developer.persisted?
developer = Developer.last
assert_equal true, developer.persisted?
developer.delete
assert_equal false, developer.persisted?
end
def test_class_level_destroy
should_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
Topic.find(1).replies << should_be_destroyed_reply
topic = Topic.destroy(1)
assert_predicate topic, :destroyed?
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1) }
assert_raise(ActiveRecord::RecordNotFound) { Reply.find(should_be_destroyed_reply.id) }
end
def test_class_level_destroy_is_affected_by_scoping
should_not_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
Topic.find(1).replies << should_not_be_destroyed_reply
assert_raise(ActiveRecord::RecordNotFound) do
Topic.where("1=0").scoping { Topic.destroy(1) }
end
assert_nothing_raised { Topic.find(1) }
assert_nothing_raised { Reply.find(should_not_be_destroyed_reply.id) }
end
def test_class_level_delete
should_not_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
Topic.find(1).replies << should_not_be_destroyed_reply
Topic.delete(1)
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1) }
assert_nothing_raised { Reply.find(should_not_be_destroyed_reply.id) }
end
def test_class_level_delete_with_invalid_ids
assert_no_queries do
assert_equal 0, Topic.delete(nil)
assert_equal 0, Topic.delete([])
end
assert_difference -> { Topic.count }, -1 do
assert_equal 1, Topic.delete(topics(:first).id)
end
end
def test_class_level_delete_is_affected_by_scoping
should_not_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
Topic.find(1).replies << should_not_be_destroyed_reply
Topic.where("1=0").scoping { Topic.delete(1) }
assert_nothing_raised { Topic.find(1) }
assert_nothing_raised { Reply.find(should_not_be_destroyed_reply.id) }
end
def test_create_with_custom_timestamps
custom_datetime = 1.hour.ago.beginning_of_day
%w(created_at created_on updated_at updated_on).each do |attribute|
parrot = LiveParrot.create(:name => "colombian", attribute => custom_datetime)
assert_equal custom_datetime, parrot[attribute]
end
end
def test_persist_inherited_class_with_different_table_name
minimalistic_aircrafts = Class.new(Minimalistic) do
self.table_name = "aircraft"
end
assert_difference "Aircraft.count", 1 do
aircraft = minimalistic_aircrafts.create(name: "Wright Flyer")
aircraft.name = "Wright Glider"
aircraft.save
end
assert_equal "Wright Glider", Aircraft.last.name
end
def test_instantiate_creates_a_new_instance
post = Post.instantiate("title" => "appropriate documentation", "type" => "SpecialPost")
assert_equal "appropriate documentation", post.title
assert_instance_of SpecialPost, post
# body was not initialized
assert_raises ActiveModel::MissingAttributeError do
post.body
end
end
def test_reload_removes_custom_selects
post = Post.select("posts.*, 1 as wibble").last!
assert_equal 1, post[:wibble]
assert_nil post.reload[:wibble]
end
def test_find_via_reload
post = Post.new
assert_predicate post, :new_record?
post.id = 1
post.reload
assert_equal "Welcome to the weblog", post.title
assert_not_predicate post, :new_record?
end
def test_reload_via_querycache
ActiveRecord::Base.lease_connection.enable_query_cache!
ActiveRecord::Base.lease_connection.clear_query_cache
assert ActiveRecord::Base.lease_connection.query_cache_enabled, "cache should be on"
parrot = Parrot.create(name: "Shane")
# populate the cache with the SELECT result
found_parrot = Parrot.find(parrot.id)
assert_equal parrot.id, found_parrot.id
# Manually update the 'name' attribute in the DB directly
assert_equal 1, ActiveRecord::Base.lease_connection.query_cache.size
ActiveRecord::Base.uncached do
found_parrot.name = "Mary"
found_parrot.save
end
# Now reload, and verify that it gets the DB version, and not the querycache version
found_parrot.reload
assert_equal "Mary", found_parrot.name
found_parrot = Parrot.find(parrot.id)
assert_equal "Mary", found_parrot.name
ensure
ActiveRecord::Base.lease_connection.disable_query_cache!
end
def test_save_touch_false
parrot = Parrot.create!(
name: "Bob",
created_at: 1.day.ago,
updated_at: 1.day.ago)
created_at = parrot.created_at
updated_at = parrot.updated_at
parrot.name = "Barb"
parrot.save!(touch: false)
assert_equal parrot.created_at, created_at
assert_equal parrot.updated_at, updated_at
end
def test_reset_column_information_resets_children
child_class = Class.new(Topic)
child_class.new # force schema to load
ActiveRecord::Base.lease_connection.add_column(:topics, :foo, :string)
Topic.reset_column_information
# this should redefine attribute methods
child_class.new
assert child_class.instance_methods.include?(:foo)
assert child_class.instance_methods.include?(:foo_changed?)
assert_equal "bar", child_class.new(foo: :bar).foo
ensure
ActiveRecord::Base.lease_connection.remove_column(:topics, :foo)
Topic.reset_column_information
end
def test_update_uses_query_constraints_config
clothing_item = clothing_items(:green_t_shirt)
sql = capture_sql { clothing_item.update(description: "Lovely green t-shirt") }.second
assert_match(/WHERE .*clothing_type/, sql)
assert_match(/WHERE .*color/, sql)
end
def test_save_uses_query_constraints_config
clothing_item = clothing_items(:green_t_shirt)
clothing_item.description = "Lovely green t-shirt"
sql = capture_sql { clothing_item.save }.second
assert_match(/WHERE .*clothing_type/, sql)
assert_match(/WHERE .*color/, sql)
end
def test_reload_uses_query_constraints_config
clothing_item = clothing_items(:green_t_shirt)
sql = capture_sql { clothing_item.reload }.first
assert_match(/WHERE .*clothing_type/, sql)
assert_match(/WHERE .*color/, sql)
end
def test_destroy_uses_query_constraints_config
clothing_item = clothing_items(:green_t_shirt)
sql = capture_sql { clothing_item.destroy }.second
assert_match(/WHERE .*clothing_type/, sql)
assert_match(/WHERE .*color/, sql)
end
def test_delete_uses_query_constraints_config
clothing_item = clothing_items(:green_t_shirt)
sql = capture_sql { clothing_item.delete }.first
assert_match(/WHERE .*clothing_type/, sql)
assert_match(/WHERE .*color/, sql)
end
def test_update_attribute_uses_query_constraints_config
clothing_item = clothing_items(:green_t_shirt)
sql = capture_sql { clothing_item.update_attribute(:description, "Lovely green t-shirt") }.second
assert_match(/WHERE .*clothing_type/, sql)
assert_match(/WHERE .*color/, sql)
end
def test_it_is_possible_to_update_parts_of_the_query_constraints_config
clothing_item = clothing_items(:green_t_shirt)
clothing_item.color = "blue"
clothing_item.description = "Now it's a blue t-shirt"
sql = capture_sql { clothing_item.save }.second
assert_match(/WHERE .*clothing_type/, sql)
assert_match(/WHERE .*color/, sql)
assert_equal("blue", ClothingItem.find_by(id: clothing_item.id).color)
end
def test_model_with_no_auto_populated_fields_still_returns_primary_key_after_insert
record = PkAutopopulatedByATriggerRecord.create
assert_not_nil record.id
assert record.id > 0
end if supports_insert_returning? && !current_adapter?(:SQLite3Adapter)
end
class QueryConstraintsTest < ActiveRecord::TestCase
fixtures :clothing_items, :dashboards, :topics, :posts
def test_primary_key_stays_the_same
assert_equal("id", ClothingItem.primary_key)
end
def test_query_constraints_list_is_nil_if_primary_key_is_nil
klass = Class.new(ActiveRecord::Base) do
self.table_name = "developers_projects"
end
assert_nil klass.primary_key
assert_nil klass.query_constraints_list
end
def test_query_constraints_list_is_nil_for_non_cpk_model
assert_nil Post.query_constraints_list
assert_nil Dashboard.query_constraints_list
end
def test_query_constraints_list_equals_to_composite_primary_key
assert_equal(["shop_id", "id"], Cpk::Order.query_constraints_list)
assert_equal(["author_id", "id"], Cpk::Book.query_constraints_list)
end
def test_child_keeps_parents_query_constraints
clothing_item = clothing_items(:green_t_shirt)
assert_uses_query_constraints_on_reload(clothing_item, ["clothing_type", "color"])
used_clothing_item = clothing_items(:used_blue_jeans)
assert_uses_query_constraints_on_reload(used_clothing_item, ["clothing_type", "color"])
end
def test_child_keeps_parents_query_contraints_derived_from_composite_pk
assert_equal(["author_id", "id"], Cpk::BestSeller.query_constraints_list)
end
def assert_uses_query_constraints_on_reload(object, columns)
flunk("columns argument must not be empty") if columns.blank?
sql = capture_sql { object.reload }.first
Array(columns).each do |column|
assert_match(/WHERE .*#{column}/, sql)
end
end
def test_query_constraints_raises_an_error_when_no_columns_provided
assert_raises(ArgumentError) do
Class.new(ActiveRecord::Base) do
self.table_name = "topics"
query_constraints
end
end
end
def test_child_class_with_query_constraints_overrides_parents
assert_equal(["clothing_type", "color", "size"], ClothingItem::Sized.query_constraints_list)
end
end
|