|
4 | 4 |
|
5 | 5 | module ActiveModelSerializers
|
6 | 6 | class CacheTest < ActiveSupport::TestCase
|
| 7 | + # Instead of a primitive cache key (i.e. a string), this class |
| 8 | + # returns a list of objects that require to be expanded themselves. |
| 9 | + class AuthorWithExpandableCacheElements < Author |
| 10 | + # For the test purposes it's important that #to_s for HasCacheKey differs |
| 11 | + # between instances, hence not a Struct. |
| 12 | + class HasCacheKey |
| 13 | + attr_reader :cache_key |
| 14 | + def initialize(cache_key) |
| 15 | + @cache_key = cache_key |
| 16 | + end |
| 17 | + |
| 18 | + def to_s |
| 19 | + "HasCacheKey##{object_id}" |
| 20 | + end |
| 21 | + end |
| 22 | + |
| 23 | + def cache_key |
| 24 | + [ |
| 25 | + HasCacheKey.new(name), |
| 26 | + HasCacheKey.new(id) |
| 27 | + ] |
| 28 | + end |
| 29 | + end |
| 30 | + |
7 | 31 | class UncachedAuthor < Author
|
8 | 32 | # To confirm cache_key is set using updated_at and cache_key option passed to cache
|
9 | 33 | undef_method :cache_key
|
@@ -106,6 +130,20 @@ def test_cache_key_interpolation_with_updated_at_when_cache_key_is_not_defined_o
|
106 | 130 | assert_equal(uncached_author_serializer.attributes.to_json, cache_store.fetch(key).to_json)
|
107 | 131 | end
|
108 | 132 |
|
| 133 | + def test_cache_key_expansion |
| 134 | + author = AuthorWithExpandableCacheElements.new(id: 10, name: 'hello') |
| 135 | + same_author = AuthorWithExpandableCacheElements.new(id: 10, name: 'hello') |
| 136 | + diff_author = AuthorWithExpandableCacheElements.new(id: 11, name: 'hello') |
| 137 | + |
| 138 | + author_serializer = AuthorSerializer.new(author) |
| 139 | + same_author_serializer = AuthorSerializer.new(same_author) |
| 140 | + diff_author_serializer = AuthorSerializer.new(diff_author) |
| 141 | + adapter = AuthorSerializer.serialization_adapter_instance |
| 142 | + |
| 143 | + assert_equal(author_serializer.cache_key(adapter), same_author_serializer.cache_key(adapter)) |
| 144 | + refute_equal(author_serializer.cache_key(adapter), diff_author_serializer.cache_key(adapter)) |
| 145 | + end |
| 146 | + |
109 | 147 | def test_default_cache_key_fallback
|
110 | 148 | render_object_with_cache(@comment)
|
111 | 149 | key = "#{@comment.cache_key}/#{adapter.cache_key}"
|
|
0 commit comments