blob: 397eae4e8aea14f64e1bacb6d214437581b29696 (
plain) (
blame)
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
|
#+TITLE: Testing Rails Components That Require Cache
#+DATE: 2023-04-28T00:14:14-04:00
#+DRAFT: false
#+DESCRIPTION: How to test rails components that require cache without caching everything
#+TAGS[]: ruby rails cache
#+KEYWORDS[]: ruby rails cache
#+SLUG:
#+SUMMARY:
If you're in the default testing environment your rails cache is
[[https://api.rubyonrails.org/classes/ActiveSupport/Cache/NullStore.html][=ActiveSupport::Cache::NullStore=]] which will always succeed but it
doesn't actually store or return anything.
There's an almost completely undocumented function called
=with_local_cache= that gets implemented on =NullStore= that lets
you run a block with a =MemoryStore= instead of a =NullStore=. This
happens because it =prepends= the
[[https://api.rubyonrails.org/classes/ActiveSupport/Cache/Strategy/LocalCache.html][=ActiveSupport::Cache::Strategy::LocalCache=]] class.
#+begin_src ruby
Rails.cache.class.name
# => "ActiveSupport::Cache::NullStore"
Rails.cache.write("a", 3)
# => true
Rails.cache.read("a")
# => nil
Rails.cache.with_local_cache do
Rails.cache.write("a", 5)
p Rails.cache.read("a")
end
5
# => 5
#+end_src
|