/
has_many_associations_test.rb
2999 lines (2367 loc) · 94.7 KB
/
has_many_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/computer"
require "models/project"
require "models/company"
require "models/contract"
require "models/topic"
require "models/reply"
require "models/category"
require "models/image"
require "models/post"
require "models/author"
require "models/essay"
require "models/comment"
require "models/person"
require "models/reader"
require "models/tagging"
require "models/tag"
require "models/invoice"
require "models/line_item"
require "models/car"
require "models/bulb"
require "models/engine"
require "models/categorization"
require "models/minivan"
require "models/speedometer"
require "models/reference"
require "models/job"
require "models/college"
require "models/student"
require "models/pirate"
require "models/ship"
require "models/ship_part"
require "models/treasure"
require "models/parrot"
require "models/tyre"
require "models/subscriber"
require "models/subscription"
require "models/zine"
require "models/interest"
class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase
fixtures :authors, :author_addresses, :posts, :comments
def test_should_generate_valid_sql
author = authors(:david)
# this can fail on adapters which require ORDER BY expressions to be included in the SELECT expression
# if the reorder clauses are not correctly handled
assert author.posts_with_comments_sorted_by_comment_id.where("comments.id > 0").reorder("posts.comments_count DESC", "posts.tags_count DESC").last
end
end
class HasManyAssociationsTestPrimaryKeys < ActiveRecord::TestCase
fixtures :authors, :author_addresses, :essays, :subscribers, :subscriptions, :people
def test_custom_primary_key_on_new_record_should_fetch_with_query
subscriber = Subscriber.new(nick: "webster132")
assert_not_predicate subscriber.subscriptions, :loaded?
assert_queries 1 do
assert_equal 2, subscriber.subscriptions.size
end
assert_equal Subscription.where(subscriber_id: "webster132"), subscriber.subscriptions
end
def test_association_primary_key_on_new_record_should_fetch_with_query
author = Author.new(name: "David")
assert_not_predicate author.essays, :loaded?
assert_queries 1 do
assert_equal 1, author.essays.size
end
assert_equal Essay.where(writer_id: "David"), author.essays
end
def test_has_many_custom_primary_key
david = authors(:david)
assert_equal Essay.where(writer_id: "David"), david.essays
end
def test_ids_on_unloaded_association_with_custom_primary_key
david = people(:david)
assert_equal Essay.where(writer_id: "David").pluck(:id), david.essay_ids
end
def test_ids_on_loaded_association_with_custom_primary_key
david = people(:david)
david.essays.load
assert_equal Essay.where(writer_id: "David").pluck(:id), david.essay_ids
end
def test_has_many_assignment_with_custom_primary_key
david = people(:david)
assert_equal ["A Modest Proposal"], david.essays.map(&:name)
david.essays = [Essay.create!(name: "Remote Work")]
assert_equal ["Remote Work"], david.essays.map(&:name)
end
def test_blank_custom_primary_key_on_new_record_should_not_run_queries
author = Author.new
assert_not_predicate author.essays, :loaded?
assert_queries 0 do
assert_equal 0, author.essays.size
end
end
end
class HasManyAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :categories, :companies, :developers, :projects,
:developers_projects, :topics, :authors, :author_addresses, :comments,
:posts, :readers, :taggings, :cars, :tags,
:categorizations, :zines, :interests
def setup
Client.destroyed_client_ids.clear
end
def test_sti_subselect_count
tag = Tag.first
len = Post.tagged_with(tag.id).limit(10).size
assert_operator len, :>, 0
end
def test_anonymous_has_many
developer = Class.new(ActiveRecord::Base) {
self.table_name = "developers"
dev = self
developer_project = Class.new(ActiveRecord::Base) {
self.table_name = "developers_projects"
belongs_to :developer, anonymous_class: dev
}
has_many :developer_projects, anonymous_class: developer_project, foreign_key: "developer_id"
}
dev = developer.first
named = Developer.find(dev.id)
assert_operator dev.developer_projects.count, :>, 0
assert_equal named.projects.map(&:id).sort,
dev.developer_projects.map(&:project_id).sort
end
def test_default_scope_on_relations_is_not_cached
counter = 0
posts = Class.new(ActiveRecord::Base) {
self.table_name = "posts"
self.inheritance_column = "not_there"
post = self
comments = Class.new(ActiveRecord::Base) {
self.table_name = "comments"
self.inheritance_column = "not_there"
belongs_to :post, anonymous_class: post
default_scope -> {
counter += 1
where("id = :inc", inc: counter)
}
}
has_many :comments, anonymous_class: comments, foreign_key: "post_id"
}
assert_equal 0, counter
post = posts.first
assert_equal 0, counter
sql = capture_sql { post.comments.to_a }
post.comments.reset
assert_not_equal sql, capture_sql { post.comments.to_a }
end
def test_has_many_build_with_options
college = College.create(name: "UFMT")
Student.create(active: true, college_id: college.id, name: "Sarah")
assert_equal college.students, Student.where(active: true, college_id: college.id)
end
def test_add_record_to_collection_should_change_its_updated_at
ship = Ship.create(name: "dauntless")
part = ShipPart.create(name: "cockpit")
updated_at = part.updated_at
travel(1.second) do
ship.parts << part
end
assert_equal part.ship, ship
assert_not_equal part.updated_at, updated_at
end
def test_clear_collection_should_not_change_updated_at
# GH#17161: .clear calls delete_all (and returns the association),
# which is intended to not touch associated objects's updated_at field
ship = Ship.create(name: "dauntless")
part = ShipPart.create(name: "cockpit", ship_id: ship.id)
ship.parts.clear
part.reload
assert_nil part.ship
assert_not_predicate part, :updated_at_changed?
end
def test_create_from_association_should_respect_default_scope
car = Car.create(name: "honda")
assert_equal "honda", car.name
bulb = Bulb.create
assert_equal "defaulty", bulb.name
bulb = car.bulbs.build
assert_equal "defaulty", bulb.name
bulb = car.bulbs.create
assert_equal "defaulty", bulb.name
bulb = car.bulbs.create!
assert_equal "defaulty", bulb.name
end
def test_build_and_create_from_association_should_respect_passed_attributes_over_default_scope
car = Car.create(name: "honda")
bulb = car.bulbs.build(name: "exotic")
assert_equal "exotic", bulb.name
bulb = car.bulbs.create(name: "exotic")
assert_equal "exotic", bulb.name
bulb = car.bulbs.create!(name: "exotic")
assert_equal "exotic", bulb.name
bulb = car.awesome_bulbs.build(frickinawesome: false)
assert_equal false, bulb.frickinawesome
bulb = car.awesome_bulbs.create(frickinawesome: false)
assert_equal false, bulb.frickinawesome
bulb = car.awesome_bulbs.create!(frickinawesome: false)
assert_equal false, bulb.frickinawesome
end
def test_build_and_create_from_association_should_respect_unscope_over_default_scope
car = Car.create(name: "honda")
bulb = car.bulbs.unscope(where: :name).build
assert_nil bulb.name
bulb = car.bulbs.unscope(where: :name).create
assert_nil bulb.name
bulb = car.bulbs.unscope(where: :name).create!
assert_nil bulb.name
bulb = car.awesome_bulbs.unscope(where: :frickinawesome).build
assert_equal false, bulb.frickinawesome
bulb = car.awesome_bulbs.unscope(where: :frickinawesome).create
assert_equal false, bulb.frickinawesome
bulb = car.awesome_bulbs.unscope(where: :frickinawesome).create!
assert_equal false, bulb.frickinawesome
end
def test_build_from_association_should_respect_scope
author = Author.new
post = author.thinking_posts.build
assert_equal "So I was thinking", post.title
end
def test_create_from_association_with_nil_values_should_work
car = Car.create(name: "honda")
bulb = car.bulbs.new(nil)
assert_equal "defaulty", bulb.name
bulb = car.bulbs.build(nil)
assert_equal "defaulty", bulb.name
bulb = car.bulbs.create(nil)
assert_equal "defaulty", bulb.name
end
def test_build_from_association_sets_inverse_instance
car = Car.new(name: "honda")
bulb = car.bulbs.build
assert_equal car, bulb.car
end
def test_do_not_call_callbacks_for_delete_all
car = Car.create(name: "honda")
car.funky_bulbs.create!
assert_equal 1, car.funky_bulbs.count
assert_equal 1, car.reload.funky_bulbs.delete_all
assert_equal 0, car.funky_bulbs.count, "bulbs should have been deleted using :delete_all strategy"
end
def test_delete_all_on_association_is_the_same_as_not_loaded
author = authors :david
author.thinking_posts.create!(body: "test")
author.reload
expected_sql = capture_sql { author.thinking_posts.delete_all }
author.thinking_posts.create!(body: "test")
author.reload
author.thinking_posts.inspect
loaded_sql = capture_sql { author.thinking_posts.delete_all }
assert_equal(expected_sql, loaded_sql)
end
def test_delete_all_on_association_with_nil_dependency_is_the_same_as_not_loaded
author = authors :david
author.posts.create!(title: "test", body: "body")
author.reload
expected_sql = capture_sql { author.posts.delete_all }
author.posts.create!(title: "test", body: "body")
author.reload
author.posts.to_a
loaded_sql = capture_sql { author.posts.delete_all }
assert_equal(expected_sql, loaded_sql)
end
def test_delete_all_on_association_clears_scope
author = Author.create!(name: "Gannon")
posts = author.posts
posts.create!(title: "test", body: "body")
posts.delete_all
assert_nil posts.first
end
def test_building_the_associated_object_with_implicit_sti_base_class
firm = DependentFirm.new
company = firm.companies.build
assert_kind_of Company, company, "Expected #{company.class} to be a Company"
end
def test_building_the_associated_object_with_explicit_sti_base_class
firm = DependentFirm.new
company = firm.companies.build(type: "Company")
assert_kind_of Company, company, "Expected #{company.class} to be a Company"
end
def test_building_the_associated_object_with_sti_subclass
firm = DependentFirm.new
company = firm.companies.build(type: "Client")
assert_kind_of Client, company, "Expected #{company.class} to be a Client"
end
def test_building_the_associated_object_with_an_invalid_type
firm = DependentFirm.new
assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Invalid") }
end
def test_building_the_associated_object_with_an_unrelated_type
firm = DependentFirm.new
assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Account") }
end
test "building the association with an array" do
speedometer = Speedometer.new(speedometer_id: "a")
data = [{ name: "first" }, { name: "second" }]
speedometer.minivans.build(data)
assert_equal 2, speedometer.minivans.size
assert speedometer.save
assert_equal ["first", "second"], speedometer.reload.minivans.map(&:name)
end
def test_association_keys_bypass_attribute_protection
car = Car.create(name: "honda")
bulb = car.bulbs.new
assert_equal car.id, bulb.car_id
bulb = car.bulbs.new car_id: car.id + 1
assert_equal car.id, bulb.car_id
bulb = car.bulbs.build
assert_equal car.id, bulb.car_id
bulb = car.bulbs.build car_id: car.id + 1
assert_equal car.id, bulb.car_id
bulb = car.bulbs.create
assert_equal car.id, bulb.car_id
bulb = car.bulbs.create car_id: car.id + 1
assert_equal car.id, bulb.car_id
end
def test_association_protect_foreign_key
invoice = Invoice.create
line_item = invoice.line_items.new
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.new invoice_id: invoice.id + 1
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.build
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.build invoice_id: invoice.id + 1
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.create
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.create invoice_id: invoice.id + 1
assert_equal invoice.id, line_item.invoice_id
end
class SpecialAuthor < ActiveRecord::Base
self.table_name = "authors"
has_many :books, class_name: "SpecialBook", foreign_key: :author_id
end
class SpecialBook < ActiveRecord::Base
self.table_name = "books"
belongs_to :author
enum read_status: { unread: 0, reading: 2, read: 3, forgotten: nil }
end
def test_association_enum_works_properly
author = SpecialAuthor.create!(name: "Test")
book = SpecialBook.create!(read_status: "reading")
author.books << book
assert_equal "reading", book.read_status
assert_not_equal 0, SpecialAuthor.joins(:books).where(books: { read_status: "reading" }).count
end
# When creating objects on the association, we must not do it within a scope (even though it
# would be convenient), because this would cause that scope to be applied to any callbacks etc.
def test_build_and_create_should_not_happen_within_scope
car = cars(:honda)
scope = car.foo_bulbs.where_values_hash
bulb = car.foo_bulbs.build
assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
bulb = car.foo_bulbs.create
assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
bulb = car.foo_bulbs.create!
assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
end
def test_no_sql_should_be_fired_if_association_already_loaded
Car.create(name: "honda")
bulbs = Car.first.bulbs
bulbs.to_a # to load all instances of bulbs
assert_no_queries do
bulbs.first()
end
assert_no_queries do
bulbs.second()
end
assert_no_queries do
bulbs.third()
end
assert_no_queries do
bulbs.fourth()
end
assert_no_queries do
bulbs.fifth()
end
assert_no_queries do
bulbs.forty_two()
end
assert_no_queries do
bulbs.third_to_last()
end
assert_no_queries do
bulbs.second_to_last()
end
assert_no_queries do
bulbs.last()
end
end
def test_finder_method_with_dirty_target
company = companies(:first_firm)
new_clients = []
assert_queries(0) do
new_clients << company.clients_of_firm.build(name: "Another Client")
new_clients << company.clients_of_firm.build(name: "Another Client II")
new_clients << company.clients_of_firm.build(name: "Another Client III")
end
assert_not_predicate company.clients_of_firm, :loaded?
assert_queries(1) do
assert_same new_clients[0], company.clients_of_firm.third
assert_same new_clients[1], company.clients_of_firm.fourth
assert_same new_clients[2], company.clients_of_firm.fifth
assert_same new_clients[0], company.clients_of_firm.third_to_last
assert_same new_clients[1], company.clients_of_firm.second_to_last
assert_same new_clients[2], company.clients_of_firm.last
end
end
def test_finder_bang_method_with_dirty_target
company = companies(:first_firm)
new_clients = []
assert_queries(0) do
new_clients << company.clients_of_firm.build(name: "Another Client")
new_clients << company.clients_of_firm.build(name: "Another Client II")
new_clients << company.clients_of_firm.build(name: "Another Client III")
end
assert_not_predicate company.clients_of_firm, :loaded?
assert_queries(1) do
assert_same new_clients[0], company.clients_of_firm.third!
assert_same new_clients[1], company.clients_of_firm.fourth!
assert_same new_clients[2], company.clients_of_firm.fifth!
assert_same new_clients[0], company.clients_of_firm.third_to_last!
assert_same new_clients[1], company.clients_of_firm.second_to_last!
assert_same new_clients[2], company.clients_of_firm.last!
end
end
def test_create_resets_cached_counters
Reader.delete_all
person = Person.create!(first_name: "tenderlove")
post = Post.first
assert_equal [], person.readers
assert_nil person.readers.find_by_post_id(post.id)
person.readers.create(post_id: post.id)
assert_equal 1, person.readers.count
assert_equal 1, person.readers.length
assert_equal post, person.readers.first.post
assert_equal person, person.readers.first.person
end
def test_update_all_respects_association_scope
person = Person.new
person.first_name = "Naruto"
person.references << Reference.new
person.save!
assert_equal 1, person.references.update_all(favourite: true)
end
def test_exists_respects_association_scope
person = Person.new
person.first_name = "Sasuke"
person.references << Reference.new
person.save!
assert_predicate person.references, :exists?
end
def test_counting_with_counter_sql
assert_equal 3, Firm.first.clients.count
end
def test_counting
assert_equal 3, Firm.first.plain_clients.count
end
def test_counting_with_single_hash
assert_equal 1, Firm.first.plain_clients.where(name: "Microsoft").count
end
def test_counting_with_column_name_and_hash
assert_equal 3, Firm.first.plain_clients.count(:name)
end
def test_counting_with_association_limit
firm = companies(:first_firm)
assert_equal firm.limited_clients.length, firm.limited_clients.size
assert_equal firm.limited_clients.length, firm.limited_clients.count
end
def test_finding
assert_equal 3, Firm.first.clients.length
end
def test_finding_array_compatibility
assert_equal 3, Firm.order(:id).find { |f| f.id > 0 }.clients.length
end
def test_find_many_with_merged_options
assert_equal 1, companies(:first_firm).limited_clients.size
assert_equal 1, companies(:first_firm).limited_clients.to_a.size
assert_equal 3, companies(:first_firm).limited_clients.limit(nil).to_a.size
end
def test_find_should_append_to_association_order
ordered_clients = companies(:first_firm).clients_sorted_desc.order("companies.id")
assert_equal ["id DESC", "companies.id"], ordered_clients.order_values
end
def test_dynamic_find_should_respect_association_order
assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.where("type = 'Client'").first
assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.find_by_type("Client")
end
def test_taking
posts(:other_by_bob).destroy
assert_equal posts(:misc_by_bob), authors(:bob).posts.take
assert_equal posts(:misc_by_bob), authors(:bob).posts.take!
authors(:bob).posts.to_a
assert_equal posts(:misc_by_bob), authors(:bob).posts.take
assert_equal posts(:misc_by_bob), authors(:bob).posts.take!
end
def test_taking_not_found
authors(:bob).posts.delete_all
assert_raise(ActiveRecord::RecordNotFound) { authors(:bob).posts.take! }
authors(:bob).posts.to_a
assert_raise(ActiveRecord::RecordNotFound) { authors(:bob).posts.take! }
end
def test_taking_with_a_number
klass = Class.new(Author) do
has_many :posts, -> { order(:id) }
def self.name
"Author"
end
end
# taking from unloaded Relation
bob = klass.find(authors(:bob).id)
new_post = bob.posts.build
assert_not_predicate bob.posts, :loaded?
assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)
assert_equal [posts(:misc_by_bob), posts(:other_by_bob), new_post], bob.posts.take(3)
# taking from loaded Relation
bob.posts.load
assert_predicate bob.posts, :loaded?
assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)
assert_equal [posts(:misc_by_bob), posts(:other_by_bob), new_post], bob.posts.take(3)
end
def test_taking_with_inverse_of
interests(:woodsmanship).destroy
interests(:survival).destroy
zine = zines(:going_out)
interest = zine.interests.take
assert_equal interests(:hunting), interest
assert_same zine, interest.zine
end
def test_cant_save_has_many_readonly_association
authors(:david).readonly_comments.each { |c| assert_raise(ActiveRecord::ReadOnlyRecord) { c.save! } }
authors(:david).readonly_comments.each { |c| assert c.readonly? }
end
def test_finding_default_orders
assert_equal "Summit", Firm.first.clients.first.name
end
def test_finding_with_different_class_name_and_order
assert_equal "Apex", Firm.first.clients_sorted_desc.first.name
end
def test_finding_with_foreign_key
assert_equal "Microsoft", Firm.first.clients_of_firm.first.name
end
def test_finding_with_condition
assert_equal "Microsoft", Firm.first.clients_like_ms.first.name
end
def test_finding_with_condition_hash
assert_equal "Microsoft", Firm.first.clients_like_ms_with_hash_conditions.first.name
end
def test_finding_using_primary_key
assert_equal "Summit", Firm.first.clients_using_primary_key.first.name
end
def test_update_all_on_association_accessed_before_save
firm = Firm.new(name: "Firm")
firm.clients << Client.first
firm.save!
assert_equal firm.clients.count, firm.clients.update_all(description: "Great!")
end
def test_update_all_on_association_accessed_before_save_with_explicit_foreign_key
firm = Firm.new(name: "Firm", id: 100)
firm.clients << Client.first
firm.save!
assert_equal firm.clients.count, firm.clients.update_all(description: "Great!")
end
def test_belongs_to_sanity
c = Client.new
assert_nil c.firm, "belongs_to failed sanity check on new object"
end
def test_find_ids
firm = Firm.first
assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find }
client = firm.clients.find(2)
assert_kind_of Client, client
client_ary = firm.clients.find([2])
assert_kind_of Array, client_ary
assert_equal client, client_ary.first
client_ary = firm.clients.find(2, 3)
assert_kind_of Array, client_ary
assert_equal 2, client_ary.size
assert_equal client, client_ary.first
assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(2, 99) }
end
def test_find_one_message_on_primary_key
firm = Firm.first
e = assert_raises(ActiveRecord::RecordNotFound) do
firm.clients.find(0)
end
assert_equal 0, e.id
assert_equal "id", e.primary_key
assert_equal "Client", e.model
assert_match (/\ACouldn't find Client with 'id'=0/), e.message
end
def test_find_ids_and_inverse_of
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
firm = companies(:first_firm)
client = firm.clients_of_firm.find(3)
assert_kind_of Client, client
client_ary = firm.clients_of_firm.find([3])
assert_kind_of Array, client_ary
assert_equal client, client_ary.first
end
def test_find_all
firm = Firm.first
assert_equal 3, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length
assert_equal 1, firm.clients.where("name = 'Summit'").to_a.length
end
def test_find_each
firm = companies(:first_firm)
assert_not_predicate firm.clients, :loaded?
assert_queries(4) do
firm.clients.find_each(batch_size: 1) { |c| assert_equal firm.id, c.firm_id }
end
assert_not_predicate firm.clients, :loaded?
end
def test_find_each_with_conditions
firm = companies(:first_firm)
assert_queries(2) do
firm.clients.where(name: "Microsoft").find_each(batch_size: 1) do |c|
assert_equal firm.id, c.firm_id
assert_equal "Microsoft", c.name
end
end
assert_not_predicate firm.clients, :loaded?
end
def test_find_in_batches
firm = companies(:first_firm)
assert_not_predicate firm.clients, :loaded?
assert_queries(2) do
firm.clients.find_in_batches(batch_size: 2) do |clients|
clients.each { |c| assert_equal firm.id, c.firm_id }
end
end
assert_not_predicate firm.clients, :loaded?
end
def test_find_all_sanitized
firm = Firm.first
summit = firm.clients.where("name = 'Summit'").to_a
assert_equal summit, firm.clients.where("name = ?", "Summit").to_a
assert_equal summit, firm.clients.where("name = :name", name: "Summit").to_a
end
def test_find_first
firm = Firm.first
client2 = Client.find(2)
assert_equal firm.clients.first, firm.clients.order("id").first
assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").order("id").first
end
def test_find_first_sanitized
firm = Firm.first
client2 = Client.find(2)
assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = ?", "Client").first
assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = :type", type: "Client").first
end
def test_find_first_after_reset_scope
firm = Firm.first
collection = firm.clients
original_object = collection.first
assert_same original_object, collection.first, "Expected second call to #first to cache the same object"
# It should return a different object, since the association has been reloaded
assert_not_same original_object, firm.clients.first, "Expected #first to return a new object"
end
def test_find_first_after_reset
firm = Firm.first
collection = firm.clients
original_object = collection.first
assert_same original_object, collection.first, "Expected second call to #first to cache the same object"
collection.reset
# It should return a different object, since the association has been reloaded
assert_not_same original_object, collection.first, "Expected #first after #reset to return a new object"
end
def test_find_first_after_reload
firm = Firm.first
collection = firm.clients
original_object = collection.first
assert_same original_object, collection.first, "Expected second call to #first to cache the same object"
collection.reload
# It should return a different object, since the association has been reloaded
assert_not_same original_object, collection.first, "Expected #first after #reload to return a new object"
end
def test_reload_with_query_cache
connection = ActiveRecord::Base.connection
connection.enable_query_cache!
connection.clear_query_cache
# Populate the cache with a query
firm = Firm.first
# Populate the cache with a second query
firm.clients.load
assert_equal 2, connection.query_cache.size
# Clear the cache and fetch the clients again, populating the cache with a query
assert_queries(1) { firm.clients.reload }
# This query is cached, so it shouldn't make a real SQL query
assert_queries(0) { firm.clients.load }
assert_equal 1, connection.query_cache.size
ensure
ActiveRecord::Base.connection.disable_query_cache!
end
def test_reloading_unloaded_associations_with_query_cache
connection = ActiveRecord::Base.connection
connection.enable_query_cache!
connection.clear_query_cache
firm = Firm.create!(name: "firm name")
client = firm.clients.create!(name: "client name")
firm.clients.to_a # add request to cache
connection.uncached do
client.update!(name: "new client name")
end
firm = Firm.find(firm.id)
assert_equal [client.name], firm.clients.reload.map(&:name)
ensure
ActiveRecord::Base.connection.disable_query_cache!
end
def test_find_all_with_include_and_conditions
assert_nothing_raised do
Developer.all.merge!(joins: :audit_logs, where: { "audit_logs.message" => nil, :name => "Smith" }).to_a
end
end
def test_find_in_collection
assert_equal Client.find(2).name, companies(:first_firm).clients.find(2).name
assert_raise(ActiveRecord::RecordNotFound) { companies(:first_firm).clients.find(6) }
end
def test_find_grouped
all_clients_of_firm1 = Client.all.merge!(where: "firm_id = 1").to_a
grouped_clients_of_firm1 = Client.all.merge!(where: "firm_id = 1", group: "firm_id", select: "firm_id, count(id) as clients_count").to_a
assert_equal 3, all_clients_of_firm1.size
assert_equal 1, grouped_clients_of_firm1.size
end
def test_find_scoped_grouped
assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.size
assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.length
assert_equal 3, companies(:first_firm).clients_grouped_by_name.size
assert_equal 3, companies(:first_firm).clients_grouped_by_name.length
end
def test_find_scoped_grouped_having
assert_equal 2, authors(:david).popular_grouped_posts.length
assert_equal 0, authors(:mary).popular_grouped_posts.length
end
def test_default_select
assert_equal Comment.column_names.sort, posts(:welcome).comments.first.attributes.keys.sort
end
def test_select_query_method
assert_equal ["id", "body"], posts(:welcome).comments.select(:id, :body).first.attributes.keys
end
def test_select_with_block
assert_equal [1], posts(:welcome).comments.select { |c| c.id == 1 }.map(&:id)
end
def test_select_with_block_and_dirty_target
assert_equal 2, posts(:welcome).comments.select { true }.size
posts(:welcome).comments.build
assert_equal 3, posts(:welcome).comments.select { true }.size
end
def test_select_without_foreign_key
assert_equal companies(:first_firm).accounts.first.credit_limit, companies(:first_firm).accounts.select(:credit_limit).first.credit_limit
end
def test_adding
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
natural = Client.new("name" => "Natural Company")
companies(:first_firm).clients_of_firm << natural
assert_equal 3, companies(:first_firm).clients_of_firm.size # checking via the collection
assert_equal 3, companies(:first_firm).clients_of_firm.reload.size # checking using the db
assert_equal natural, companies(:first_firm).clients_of_firm.last
end
def test_adding_using_create
first_firm = companies(:first_firm)
assert_equal 3, first_firm.plain_clients.size
first_firm.plain_clients.create(name: "Natural Company")
assert_equal 4, first_firm.plain_clients.length
assert_equal 4, first_firm.plain_clients.size
end
def test_create_with_bang_on_has_many_when_parent_is_new_raises
error = assert_raise(ActiveRecord::RecordNotSaved) do
firm = Firm.new
firm.plain_clients.create! name: "Whoever"
end
assert_equal "You cannot call create unless the parent is saved", error.message
end
def test_regular_create_on_has_many_when_parent_is_new_raises
error = assert_raise(ActiveRecord::RecordNotSaved) do
firm = Firm.new
firm.plain_clients.create name: "Whoever"
end
assert_equal "You cannot call create unless the parent is saved", error.message
end
def test_create_with_bang_on_has_many_raises_when_record_not_saved
assert_raise(ActiveRecord::RecordInvalid) do
firm = Firm.first