-
Notifications
You must be signed in to change notification settings - Fork 21.4k
/
belongs_to_associations_test.rb
1493 lines (1159 loc) · 44.7 KB
/
belongs_to_associations_test.rb
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
# frozen_string_literal: true
require "cases/helper"
require "models/developer"
require "models/project"
require "models/company"
require "models/topic"
require "models/reply"
require "models/computer"
require "models/post"
require "models/author"
require "models/tag"
require "models/tagging"
require "models/comment"
require "models/sponsor"
require "models/member"
require "models/essay"
require "models/toy"
require "models/invoice"
require "models/line_item"
require "models/column"
require "models/record"
require "models/admin"
require "models/admin/user"
require "models/ship"
require "models/treasure"
require "models/parrot"
require "models/book"
require "models/citation"
class BelongsToAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :developers, :projects, :topics,
:developers_projects, :computers, :authors, :author_addresses,
:essays, :posts, :tags, :taggings, :comments, :sponsors, :members
def test_belongs_to
client = Client.find(3)
first_firm = companies(:first_firm)
assert_sql(/LIMIT|ROWNUM <=|FETCH FIRST/) do
assert_equal first_firm, client.firm
assert_equal first_firm.name, client.firm.name
end
end
def test_where_with_custom_primary_key
assert_equal [authors(:david)], Author.where(owned_essay: essays(:david_modest_proposal))
end
def test_find_by_with_custom_primary_key
assert_equal authors(:david), Author.find_by(owned_essay: essays(:david_modest_proposal))
end
def test_where_on_polymorphic_association_with_nil
assert_equal comments(:greetings), Comment.where(author: nil).first
assert_equal comments(:greetings), Comment.where(author: [nil]).first
end
def test_where_on_polymorphic_association_with_empty_array
assert_empty Comment.where(author: [])
end
def test_assigning_belongs_to_on_destroyed_object
client = Client.create!(name: "Client")
client.destroy!
assert_raise(FrozenError) { client.firm = nil }
assert_raise(FrozenError) { client.firm = Firm.new(name: "Firm") }
end
def test_eager_loading_wont_mutate_owner_record
client = Client.eager_load(:firm_with_basic_id).first
assert_not_predicate client, :firm_id_came_from_user?
client = Client.preload(:firm_with_basic_id).first
assert_not_predicate client, :firm_id_came_from_user?
end
def test_missing_attribute_error_is_raised_when_no_foreign_key_attribute
assert_raises(ActiveModel::MissingAttributeError) { Client.select(:id).first.firm }
end
def test_belongs_to_does_not_use_order_by
sql_log = capture_sql { Client.find(3).firm }
assert sql_log.all? { |sql| !/order by/i.match?(sql) }, "ORDER BY was used in the query: #{sql_log}"
end
def test_belongs_to_with_primary_key
client = Client.create(name: "Primary key client", firm_name: companies(:first_firm).name)
assert_equal companies(:first_firm).name, client.firm_with_primary_key.name
end
def test_belongs_to_with_primary_key_joins_on_correct_column
sql = Client.joins(:firm_with_primary_key).to_sql
if current_adapter?(:Mysql2Adapter)
assert_no_match(/`firm_with_primary_keys_companies`\.`id`/, sql)
assert_match(/`firm_with_primary_keys_companies`\.`name`/, sql)
elsif current_adapter?(:OracleAdapter)
# on Oracle aliases are truncated to 30 characters and are quoted in uppercase
assert_no_match(/"firm_with_primary_keys_compani"\."id"/i, sql)
assert_match(/"firm_with_primary_keys_compani"\."name"/i, sql)
else
assert_no_match(/"firm_with_primary_keys_companies"\."id"/, sql)
assert_match(/"firm_with_primary_keys_companies"\."name"/, sql)
end
end
def test_optional_relation_can_be_set_per_model
model1 = Class.new(ActiveRecord::Base) do
self.table_name = "accounts"
self.belongs_to_required_by_default = false
belongs_to :company
def self.name
"FirstModel"
end
end.new
model2 = Class.new(ActiveRecord::Base) do
self.table_name = "accounts"
self.belongs_to_required_by_default = true
belongs_to :company
def self.name
"SecondModel"
end
end.new
assert_predicate model1, :valid?
assert_not_predicate model2, :valid?
end
def test_optional_relation
original_value = ActiveRecord::Base.belongs_to_required_by_default
ActiveRecord::Base.belongs_to_required_by_default = true
model = Class.new(ActiveRecord::Base) do
self.table_name = "accounts"
def self.name; "Temp"; end
belongs_to :company, optional: true
end
account = model.new
assert_predicate account, :valid?
ensure
ActiveRecord::Base.belongs_to_required_by_default = original_value
end
def test_not_optional_relation
original_value = ActiveRecord::Base.belongs_to_required_by_default
ActiveRecord::Base.belongs_to_required_by_default = true
model = Class.new(ActiveRecord::Base) do
self.table_name = "accounts"
def self.name; "Temp"; end
belongs_to :company, optional: false
end
account = model.new
assert_not_predicate account, :valid?
assert_equal [{ error: :blank }], account.errors.details[:company]
ensure
ActiveRecord::Base.belongs_to_required_by_default = original_value
end
def test_required_belongs_to_config
original_value = ActiveRecord::Base.belongs_to_required_by_default
ActiveRecord::Base.belongs_to_required_by_default = true
model = Class.new(ActiveRecord::Base) do
self.table_name = "accounts"
def self.name; "Temp"; end
belongs_to :company
end
account = model.new
assert_not_predicate account, :valid?
assert_equal [{ error: :blank }], account.errors.details[:company]
ensure
ActiveRecord::Base.belongs_to_required_by_default = original_value
end
def test_default
david = developers(:david)
jamis = developers(:jamis)
model = Class.new(ActiveRecord::Base) do
self.table_name = "ships"
def self.name; "Temp"; end
belongs_to :developer, default: -> { david }
end
ship = model.create!
assert_equal david, ship.developer
ship = model.create!(developer: jamis)
assert_equal jamis, ship.developer
ship.update!(developer: nil)
assert_equal david, ship.developer
end
def test_default_with_lambda
model = Class.new(ActiveRecord::Base) do
self.table_name = "ships"
def self.name; "Temp"; end
belongs_to :developer, default: -> { default_developer }
def default_developer
Developer.first
end
end
ship = model.create!
assert_equal developers(:david), ship.developer
ship = model.create!(developer: developers(:jamis))
assert_equal developers(:jamis), ship.developer
end
def test_default_scope_on_relations_is_not_cached
counter = 0
comments = Class.new(ActiveRecord::Base) {
self.table_name = "comments"
self.inheritance_column = "not_there"
posts = Class.new(ActiveRecord::Base) {
self.table_name = "posts"
self.inheritance_column = "not_there"
default_scope -> {
counter += 1
where("id = :inc", inc: counter)
}
has_many :comments, anonymous_class: comments
}
belongs_to :post, anonymous_class: posts, inverse_of: false
}
assert_equal 0, counter
comment = comments.first
assert_equal 0, counter
sql = capture_sql { comment.post }
comment.reload
assert_not_equal sql, capture_sql { comment.post }
end
def test_proxy_assignment
account = Account.find(1)
assert_nothing_raised { account.firm = account.firm }
end
def test_type_mismatch
assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = 1 }
assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = Project.find(1) }
end
def test_raises_type_mismatch_with_namespaced_class
assert_nil defined?(Region), "This test requires that there is no top-level Region class"
ActiveRecord::Base.connection.instance_eval do
create_table(:admin_regions, force: true) { |t| t.string :name }
add_column :admin_users, :region_id, :integer
end
Admin.const_set "RegionalUser", Class.new(Admin::User) { belongs_to(:region) }
Admin.const_set "Region", Class.new(ActiveRecord::Base)
e = assert_raise(ActiveRecord::AssociationTypeMismatch) {
Admin::RegionalUser.new(region: "wrong value")
}
assert_match(/^Region\([^)]+\) expected, got "wrong value" which is an instance of String\([^)]+\)$/, e.message)
ensure
Admin.send :remove_const, "Region" if Admin.const_defined?("Region")
Admin.send :remove_const, "RegionalUser" if Admin.const_defined?("RegionalUser")
ActiveRecord::Base.connection.instance_eval do
remove_column :admin_users, :region_id if column_exists?(:admin_users, :region_id)
drop_table :admin_regions, if_exists: true
end
Admin::User.reset_column_information
end
def test_natural_assignment
apple = Firm.create("name" => "Apple")
citibank = Account.create("credit_limit" => 10)
citibank.firm = apple
assert_equal apple.id, citibank.firm_id
end
def test_id_assignment
apple = Firm.create("name" => "Apple")
citibank = Account.create("credit_limit" => 10)
citibank.firm_id = apple
assert_nil citibank.firm_id
end
def test_natural_assignment_with_primary_key
apple = Firm.create("name" => "Apple")
citibank = Client.create("name" => "Primary key client")
citibank.firm_with_primary_key = apple
assert_equal apple.name, citibank.firm_name
end
def test_eager_loading_with_primary_key
Firm.create("name" => "Apple")
Client.create("name" => "Citibank", :firm_name => "Apple")
citibank_result = Client.all.merge!(where: { name: "Citibank" }, includes: :firm_with_primary_key).first
assert_predicate citibank_result.association(:firm_with_primary_key), :loaded?
end
def test_eager_loading_with_primary_key_as_symbol
Firm.create("name" => "Apple")
Client.create("name" => "Citibank", :firm_name => "Apple")
citibank_result = Client.all.merge!(where: { name: "Citibank" }, includes: :firm_with_primary_key_symbols).first
assert_predicate citibank_result.association(:firm_with_primary_key_symbols), :loaded?
end
def test_creating_the_belonging_object
citibank = Account.create("credit_limit" => 10)
apple = citibank.create_firm("name" => "Apple")
assert_equal apple, citibank.firm
citibank.save
citibank.reload
assert_equal apple, citibank.firm
end
def test_creating_the_belonging_object_from_new_record
citibank = Account.new("credit_limit" => 10)
apple = citibank.create_firm("name" => "Apple")
assert_equal apple, citibank.firm
citibank.save
citibank.reload
assert_equal apple, citibank.firm
end
def test_creating_the_belonging_object_with_primary_key
client = Client.create(name: "Primary key client")
apple = client.create_firm_with_primary_key("name" => "Apple")
assert_equal apple, client.firm_with_primary_key
client.save
client.reload
assert_equal apple, client.firm_with_primary_key
end
def test_building_the_belonging_object
citibank = Account.create("credit_limit" => 10)
apple = citibank.build_firm("name" => "Apple")
citibank.save
assert_equal apple.id, citibank.firm_id
end
def test_building_the_belonging_object_with_implicit_sti_base_class
account = Account.new
company = account.build_firm
assert_kind_of Company, company, "Expected #{company.class} to be a Company"
end
def test_building_the_belonging_object_with_explicit_sti_base_class
account = Account.new
company = account.build_firm(type: "Company")
assert_kind_of Company, company, "Expected #{company.class} to be a Company"
end
def test_building_the_belonging_object_with_sti_subclass
account = Account.new
company = account.build_firm(type: "Firm")
assert_kind_of Firm, company, "Expected #{company.class} to be a Firm"
end
def test_building_the_belonging_object_with_an_invalid_type
account = Account.new
assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(type: "InvalidType") }
end
def test_building_the_belonging_object_with_an_unrelated_type
account = Account.new
assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(type: "Account") }
end
def test_building_the_belonging_object_with_primary_key
client = Client.create(name: "Primary key client")
apple = client.build_firm_with_primary_key("name" => "Apple")
client.save
assert_equal apple.name, client.firm_name
end
def test_create!
client = Client.create!(name: "Jimmy")
account = client.create_account!(credit_limit: 10)
assert_equal account, client.account
assert_predicate account, :persisted?
client.save
client.reload
assert_equal account, client.account
end
def test_failing_create!
client = Client.create!(name: "Jimmy")
assert_raise(ActiveRecord::RecordInvalid) { client.create_account! }
assert_not_nil client.account
assert_predicate client.account, :new_record?
end
def test_reloading_the_belonging_object
odegy_account = accounts(:odegy_account)
assert_equal "Odegy", odegy_account.firm.name
Company.where(id: odegy_account.firm_id).update_all(name: "ODEGY")
assert_equal "Odegy", odegy_account.firm.name
assert_equal "ODEGY", odegy_account.reload_firm.name
end
def test_reload_the_belonging_object_with_query_cache
odegy_account_id = accounts(:odegy_account).id
connection = ActiveRecord::Base.connection
connection.enable_query_cache!
connection.clear_query_cache
# Populate the cache with a query
odegy_account = Account.find(odegy_account_id)
# Populate the cache with a second query
odegy_account.firm
assert_equal 2, connection.query_cache.size
# Clear the cache and fetch the firm again, populating the cache with a query
assert_queries(1) { odegy_account.reload_firm }
# This query is not cached anymore, so it should make a real SQL query
assert_queries(1) { Account.find(odegy_account_id) }
ensure
ActiveRecord::Base.connection.disable_query_cache!
end
def test_natural_assignment_to_nil
client = Client.find(3)
client.firm = nil
client.save
client.association(:firm).reload
assert_nil client.firm
assert_nil client.client_of
end
def test_natural_assignment_to_nil_with_primary_key
client = Client.create(name: "Primary key client", firm_name: companies(:first_firm).name)
client.firm_with_primary_key = nil
client.save
client.association(:firm_with_primary_key).reload
assert_nil client.firm_with_primary_key
assert_nil client.client_of
end
def test_with_different_class_name
assert_equal Company.find(1).name, Company.find(3).firm_with_other_name.name
assert_not_nil Company.find(3).firm_with_other_name, "Microsoft should have a firm"
end
def test_with_condition
assert_equal Company.find(1).name, Company.find(3).firm_with_condition.name
assert_not_nil Company.find(3).firm_with_condition, "Microsoft should have a firm"
end
def test_polymorphic_association_class
sponsor = Sponsor.new
assert_nil sponsor.association(:sponsorable).klass
sponsor.association(:sponsorable).reload
assert_nil sponsor.sponsorable
sponsor.sponsorable_type = "" # the column doesn't have to be declared NOT NULL
assert_nil sponsor.association(:sponsorable).klass
sponsor.association(:sponsorable).reload
assert_nil sponsor.sponsorable
sponsor.sponsorable = Member.new name: "Bert"
assert_equal Member, sponsor.association(:sponsorable).klass
end
def test_with_polymorphic_and_condition
sponsor = Sponsor.create
member = Member.create name: "Bert"
sponsor.sponsorable = member
sponsor.save!
assert_equal member, sponsor.sponsorable
assert_nil sponsor.sponsorable_with_conditions
sponsor = Sponsor.preload(:sponsorable, :sponsorable_with_conditions).last
assert_equal member, sponsor.sponsorable
assert_nil sponsor.sponsorable_with_conditions
end
def test_with_select
assert_equal 1, Post.find(2).author_with_select.attributes.size
assert_equal 1, Post.includes(:author_with_select).find(2).author_with_select.attributes.size
end
def test_custom_attribute_with_select
assert_equal 2, Company.find(2).firm_with_select.attributes.size
assert_equal 2, Company.includes(:firm_with_select).find(2).firm_with_select.attributes.size
end
def test_belongs_to_without_counter_cache_option
# Ship has a conventionally named `treasures_count` column, but the counter_cache
# option is not given on the association.
ship = Ship.create(name: "Countless")
assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed unless counter_cache is given on the relation" do
treasure = Treasure.new(name: "Gold", ship: ship)
treasure.save
end
assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed unless counter_cache is given on the relation" do
treasure = ship.treasures.first
treasure.destroy
end
end
def test_belongs_to_counter
debate = Topic.create("title" => "debate")
assert_equal 0, debate.read_attribute("replies_count"), "No replies yet"
trash = debate.replies.create("title" => "blah!", "content" => "world around!")
assert_equal 1, Topic.find(debate.id).read_attribute("replies_count"), "First reply created"
trash.destroy
assert_equal 0, Topic.find(debate.id).read_attribute("replies_count"), "First reply deleted"
end
def test_belongs_to_counter_with_assigning_nil
topic = Topic.create!(title: "debate")
reply = Reply.create!(title: "blah!", content: "world around!", topic: topic)
assert_equal topic.id, reply.parent_id
assert_equal 1, topic.reload.replies.size
reply.topic = nil
reply.reload
assert_equal topic.id, reply.parent_id
assert_equal 1, topic.reload.replies.size
reply.topic = nil
reply.save!
assert_equal 0, topic.reload.replies.size
end
def test_belongs_to_counter_with_assigning_new_object
topic = Topic.create!(title: "debate")
reply = Reply.create!(title: "blah!", content: "world around!", topic: topic)
assert_equal topic.id, reply.parent_id
assert_equal 1, topic.reload.replies_count
topic2 = reply.build_topic(title: "debate2")
reply.save!
assert_not_equal topic.id, reply.parent_id
assert_equal topic2.id, reply.parent_id
assert_equal 0, topic.reload.replies_count
assert_equal 1, topic2.reload.replies_count
end
def test_belongs_to_with_primary_key_counter
debate = Topic.create("title" => "debate")
debate2 = Topic.create("title" => "debate2")
reply = Reply.create("title" => "blah!", "content" => "world around!", "parent_title" => "debate2")
assert_equal 0, debate.reload.replies_count
assert_equal 1, debate2.reload.replies_count
reply.parent_title = "debate"
reply.save!
assert_equal 1, debate.reload.replies_count
assert_equal 0, debate2.reload.replies_count
assert_no_queries do
reply.topic_with_primary_key = debate
end
assert_equal 1, debate.reload.replies_count
assert_equal 0, debate2.reload.replies_count
reply.topic_with_primary_key = debate2
reply.save!
assert_equal 0, debate.reload.replies_count
assert_equal 1, debate2.reload.replies_count
reply.topic_with_primary_key = nil
reply.save!
assert_equal 0, debate.reload.replies_count
assert_equal 0, debate2.reload.replies_count
end
def test_belongs_to_counter_with_reassigning
topic1 = Topic.create("title" => "t1")
topic2 = Topic.create("title" => "t2")
reply1 = Reply.new("title" => "r1", "content" => "r1")
reply1.topic = topic1
assert reply1.save
assert_equal 1, Topic.find(topic1.id).replies.size
assert_equal 0, Topic.find(topic2.id).replies.size
reply1.topic = Topic.find(topic2.id)
assert_no_queries do
reply1.topic = topic2
end
assert reply1.save
assert_equal 0, Topic.find(topic1.id).replies.size
assert_equal 1, Topic.find(topic2.id).replies.size
reply1.topic = nil
reply1.save!
assert_equal 0, Topic.find(topic1.id).replies.size
assert_equal 0, Topic.find(topic2.id).replies.size
reply1.topic = topic1
reply1.save!
assert_equal 1, Topic.find(topic1.id).replies.size
assert_equal 0, Topic.find(topic2.id).replies.size
reply1.destroy
assert_equal 0, Topic.find(topic1.id).replies.size
assert_equal 0, Topic.find(topic2.id).replies.size
end
def test_belongs_to_reassign_with_namespaced_models_and_counters
topic1 = Web::Topic.create("title" => "t1")
topic2 = Web::Topic.create("title" => "t2")
reply1 = Web::Reply.new("title" => "r1", "content" => "r1")
reply1.topic = topic1
assert reply1.save
assert_equal 1, Web::Topic.find(topic1.id).replies.size
assert_equal 0, Web::Topic.find(topic2.id).replies.size
reply1.topic = Web::Topic.find(topic2.id)
assert reply1.save
assert_equal 0, Web::Topic.find(topic1.id).replies.size
assert_equal 1, Web::Topic.find(topic2.id).replies.size
end
def test_belongs_to_counter_after_save
topic = Topic.create!(title: "monday night")
assert_queries(2) do
topic.replies.create!(title: "re: monday night", content: "football")
end
assert_equal 1, Topic.find(topic.id)[:replies_count]
topic.save!
assert_equal 1, Topic.find(topic.id)[:replies_count]
end
def test_belongs_to_counter_after_touch
topic = Topic.create!(title: "topic")
assert_equal 0, topic.replies_count
assert_equal 0, topic.after_touch_called
reply = Reply.create!(title: "blah!", content: "world around!", topic_with_primary_key: topic)
assert_equal 1, topic.replies_count
assert_equal 1, topic.after_touch_called
reply.destroy!
assert_equal 0, topic.replies_count
assert_equal 2, topic.after_touch_called
end
def test_belongs_to_touch_with_reassigning
debate = Topic.create!(title: "debate")
debate2 = Topic.create!(title: "debate2")
reply = Reply.create!(title: "blah!", content: "world around!", parent_title: "debate2")
time = 1.day.ago
debate.touch(time: time)
debate2.touch(time: time)
assert_queries(3) do
reply.parent_title = "debate"
reply.save!
end
assert_operator debate.reload.updated_at, :>, time
assert_operator debate2.reload.updated_at, :>, time
debate.touch(time: time)
debate2.touch(time: time)
assert_queries(3) do
reply.topic_with_primary_key = debate2
reply.save!
end
assert_operator debate.reload.updated_at, :>, time
assert_operator debate2.reload.updated_at, :>, time
end
def test_belongs_to_with_touch_option_on_touch
line_item = LineItem.create!
Invoice.create!(line_items: [line_item])
assert_queries(1) { line_item.touch }
end
def test_belongs_to_with_touch_on_multiple_records
line_item = LineItem.create!(amount: 1)
line_item2 = LineItem.create!(amount: 2)
Invoice.create!(line_items: [line_item, line_item2])
assert_queries(1) do
LineItem.transaction do
line_item.touch
line_item2.touch
end
end
assert_queries(2) do
line_item.touch
line_item2.touch
end
end
def test_belongs_to_with_touch_option_on_touch_without_updated_at_attributes
assert_not LineItem.column_names.include?("updated_at")
line_item = LineItem.create!
invoice = Invoice.create!(line_items: [line_item])
initial = invoice.updated_at
travel(1.second) do
line_item.touch
end
assert_not_equal initial, invoice.reload.updated_at
end
def test_belongs_to_with_touch_option_on_touch_and_removed_parent
line_item = LineItem.create!
Invoice.create!(line_items: [line_item])
line_item.invoice = nil
assert_queries(2) { line_item.touch }
end
def test_belongs_to_with_touch_option_on_update
line_item = LineItem.create!
Invoice.create!(line_items: [line_item])
assert_queries(2) { line_item.update amount: 10 }
end
def test_belongs_to_with_touch_option_on_empty_update
line_item = LineItem.create!
Invoice.create!(line_items: [line_item])
assert_no_queries { line_item.save }
end
def test_belongs_to_with_touch_option_on_destroy
line_item = LineItem.create!
Invoice.create!(line_items: [line_item])
assert_queries(2) { line_item.destroy }
end
def test_belongs_to_with_touch_option_on_destroy_with_destroyed_parent
line_item = LineItem.create!
invoice = Invoice.create!(line_items: [line_item])
invoice.destroy
assert_queries(1) { line_item.destroy }
end
def test_belongs_to_with_touch_option_on_touch_and_reassigned_parent
line_item = LineItem.create!
Invoice.create!(line_items: [line_item])
line_item.invoice = Invoice.create!
assert_queries(3) { line_item.touch }
end
def test_belongs_to_counter_after_update
topic = Topic.create!(title: "37s")
topic.replies.create!(title: "re: 37s", content: "rails")
assert_equal 1, Topic.find(topic.id)[:replies_count]
topic.update(title: "37signals")
assert_equal 1, Topic.find(topic.id)[:replies_count]
end
def test_belongs_to_counter_when_update_columns
topic = Topic.create!(title: "37s")
topic.replies.create!(title: "re: 37s", content: "rails")
assert_equal 1, Topic.find(topic.id)[:replies_count]
topic.update_columns(content: "rails is wonderful")
assert_equal 1, Topic.find(topic.id)[:replies_count]
end
def test_assignment_before_child_saved
final_cut = Client.new("name" => "Final Cut")
firm = Firm.find(1)
final_cut.firm = firm
assert_not_predicate final_cut, :persisted?
assert final_cut.save
assert_predicate final_cut, :persisted?
assert_predicate firm, :persisted?
assert_equal firm, final_cut.firm
final_cut.association(:firm).reload
assert_equal firm, final_cut.firm
end
def test_assignment_before_child_saved_with_primary_key
final_cut = Client.new("name" => "Final Cut")
firm = Firm.find(1)
final_cut.firm_with_primary_key = firm
assert_not_predicate final_cut, :persisted?
assert final_cut.save
assert_predicate final_cut, :persisted?
assert_predicate firm, :persisted?
assert_equal firm, final_cut.firm_with_primary_key
final_cut.association(:firm_with_primary_key).reload
assert_equal firm, final_cut.firm_with_primary_key
end
def test_new_record_with_foreign_key_but_no_object
client = Client.new("firm_id" => 1)
assert_equal Firm.first, client.firm_with_basic_id
end
def test_setting_foreign_key_after_nil_target_loaded
client = Client.new
client.firm_with_basic_id
client.firm_id = 1
assert_equal companies(:first_firm), client.firm_with_basic_id
end
def test_polymorphic_setting_foreign_key_after_nil_target_loaded
sponsor = Sponsor.new
sponsor.sponsorable
sponsor.sponsorable_id = 1
sponsor.sponsorable_type = "Member"
assert_equal members(:groucho), sponsor.sponsorable
end
def test_dont_find_target_when_foreign_key_is_null
tagging = taggings(:thinking_general)
assert_no_queries { tagging.super_tag }
end
def test_dont_find_target_when_saving_foreign_key_after_stale_association_loaded
client = Client.create!(name: "Test client", firm_with_basic_id: Firm.find(1))
client.firm_id = Firm.create!(name: "Test firm").id
assert_queries(1) { client.save! }
end
def test_field_name_same_as_foreign_key
computer = Computer.find(1)
assert_not_nil computer.developer, ":foreign key == attribute didn't lock up" # '
end
def test_counter_cache
topic = Topic.create title: "Zoom-zoom-zoom"
assert_equal 0, topic[:replies_count]
reply = Reply.create(title: "re: zoom", content: "speedy quick!")
reply.topic = topic
reply.save!
assert_equal 1, topic.reload[:replies_count]
assert_equal 1, topic.replies.size
topic[:replies_count] = 15
assert_equal 15, topic.replies.size
end
def test_counter_cache_double_destroy
topic = Topic.create title: "Zoom-zoom-zoom"
5.times do
topic.replies.create(title: "re: zoom", content: "speedy quick!")
end
assert_equal 5, topic.reload[:replies_count]
assert_equal 5, topic.replies.size
reply = topic.replies.first
reply.destroy
assert_equal 4, topic.reload[:replies_count]
reply.destroy
assert_equal 4, topic.reload[:replies_count]
assert_equal 4, topic.replies.size
end
def test_concurrent_counter_cache_double_destroy
topic = Topic.create title: "Zoom-zoom-zoom"
5.times do
topic.replies.create(title: "re: zoom", content: "speedy quick!")
end
assert_equal 5, topic.reload[:replies_count]
assert_equal 5, topic.replies.size
reply = topic.replies.first
reply_clone = Reply.find(reply.id)
reply.destroy
assert_equal 4, topic.reload[:replies_count]
reply_clone.destroy
assert_equal 4, topic.reload[:replies_count]
assert_equal 4, topic.replies.size
end
def test_custom_counter_cache
reply = Reply.create(title: "re: zoom", content: "speedy quick!")
assert_equal 0, reply[:replies_count]
silly = SillyReply.create(title: "gaga", content: "boo-boo")
silly.reply = reply
silly.save!
assert_equal 1, reply.reload[:replies_count]
assert_equal 1, reply.replies.size
reply[:replies_count] = 17
assert_equal 17, reply.replies.size
end
def test_replace_counter_cache
topic = Topic.create(title: "Zoom-zoom-zoom")
reply = Reply.create(title: "re: zoom", content: "speedy quick!")
reply.topic = topic
reply.save
topic.reload
assert_equal 1, topic.replies_count
end
def test_association_assignment_sticks
post = Post.first
author1, author2 = Author.all.merge!(limit: 2).to_a
assert_not_nil author1
assert_not_nil author2
# make sure the association is loaded
post.author
# set the association by id, directly
post.author_id = author2.id
# save and reload
post.save!
post.reload
# the author id of the post should be the id we set
assert_equal post.author_id, author2.id
end
def test_cant_save_readonly_association
assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_client).readonly_firm.save! }
assert_predicate companies(:first_client).readonly_firm, :readonly?
end
def test_polymorphic_assignment_foreign_key_type_string
comment = Comment.first
comment.author = Author.first
comment.resource = Member.first