@@ -423,5 +423,57 @@ def test_mutating_reflection_block_is_not_thread_safe
423
423
end
424
424
# rubocop:enable Metrics/AbcSize
425
425
end
426
+ class ThreadedReflectionTest < ActiveSupport ::TestCase
427
+ class Post < ::Model
428
+ attributes :id , :title , :body
429
+ associations :comments
430
+ end
431
+ class Comment < ::Model
432
+ attributes :id , :body
433
+ associations :post
434
+ end
435
+ class CommentSerializer < ActiveModel ::Serializer
436
+ type 'comment'
437
+ attributes :id , :body
438
+ has_one :post
439
+ end
440
+ class PostSerializer < ActiveModel ::Serializer
441
+ type 'post'
442
+ attributes :id , :title , :body
443
+ has_many :comments , serializer : CommentSerializer do
444
+ sleep 0.1
445
+ object . comments
446
+ end
447
+ end
448
+
449
+ # per https://github.com/rails-api/active_model_serializers/issues/2270
450
+ def test_concurrent_serialization
451
+ post1 = Post . new ( id : 1 , title : 'Post 1 Title' , body : 'Post 1 Body' )
452
+ post1 . comments = [ Comment . new ( id : 1 , body : 'Comment on Post 1' , post : post1 ) ]
453
+ post2 = Post . new ( id : 2 , title : 'Post 2 Title' , body : 'Post 2 Body' )
454
+ post2 . comments = [ Comment . new ( id : 2 , body : 'Comment on Post 2' , post : post2 ) ]
455
+ serialized_posts = {
456
+ first : Set . new ,
457
+ second : Set . new
458
+ }
459
+ t1 = Thread . new do
460
+ 10 . times do
461
+ serialized_posts [ :first ] << PostSerializer . new ( post1 , { } ) . to_json
462
+ end
463
+ end
464
+ t2 = Thread . new do
465
+ 10 . times do
466
+ serialized_posts [ :second ] << PostSerializer . new ( post2 , { } ) . to_json
467
+ end
468
+ end
469
+ t1 . join
470
+ t2 . join
471
+ expected_first_post_serialization = '{"id":1,"title":"Post 1 Title","body":"Post 1 Body","comments":[{"id":1,"body":"Comment on Post 1"}]}'
472
+ expected_second_post_serialization = '{"id":2,"title":"Post 2 Title","body":"Post 2 Body","comments":[{"id":2,"body":"Comment on Post 2"}]}'
473
+
474
+ assert_equal [ expected_second_post_serialization ] , serialized_posts [ :second ] . to_a
475
+ assert_equal [ expected_first_post_serialization ] , serialized_posts [ :first ] . to_a
476
+ end
477
+ end
426
478
end
427
479
end
0 commit comments