mirror of
https://github.com/jbranchaud/til
synced 2026-01-07 17:18:02 +00:00
Add Use Specific Cache Store In A Single Test as an RSpec til
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
|||||||
|
|
||||||
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||||
|
|
||||||
_1181 TILs and counting..._
|
_1182 TILs and counting..._
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -893,6 +893,7 @@ _1181 TILs and counting..._
|
|||||||
|
|
||||||
- [Check Specific Arguments To Received Method](rspec/check-specific-arguments-to-received-method.md)
|
- [Check Specific Arguments To Received Method](rspec/check-specific-arguments-to-received-method.md)
|
||||||
- [Find Minimal Set Of Tests Causing A Flicker](rspec/find-minimal-set-of-tests-causing-a-flicker.md)
|
- [Find Minimal Set Of Tests Causing A Flicker](rspec/find-minimal-set-of-tests-causing-a-flicker.md)
|
||||||
|
- [Use Specific Cache Store In A Single Test](rspec/use-specific-cache-store-in-a-single-test.md)
|
||||||
|
|
||||||
### Ruby
|
### Ruby
|
||||||
|
|
||||||
|
|||||||
41
rspec/use-specific-cache-store-in-a-single-test.md
Normal file
41
rspec/use-specific-cache-store-in-a-single-test.md
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
# Use Specific Cache Store In A Single Test
|
||||||
|
|
||||||
|
It is generally recommended to use `:null_store` as the default cache store
|
||||||
|
across your test suite. This is defined in `config/environments/test.rb`.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
config.cache_store = :null_store
|
||||||
|
```
|
||||||
|
|
||||||
|
This generally simplifies tests by avoiding confusing stateful scenarios.
|
||||||
|
|
||||||
|
If there is a test where you want to observe specific caching behavior, then
|
||||||
|
you'll need to temporarily swap that for another store.
|
||||||
|
|
||||||
|
One way to do that is by mocking the cache with `MemoryStore` in a before
|
||||||
|
block.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
describe '#caching_feature' do
|
||||||
|
# use MemoryStore cache for these tests
|
||||||
|
before do
|
||||||
|
allow(Rails)
|
||||||
|
.to receive(:cache)
|
||||||
|
.and_return(ActiveSupport::Cache::MemoryStore.new)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does caching' do
|
||||||
|
thing = Thing.caching_feature(1)
|
||||||
|
|
||||||
|
expect(thing.value).to eq true
|
||||||
|
|
||||||
|
thing.update(value: false)
|
||||||
|
|
||||||
|
thing = Thing.caching_feature(1)
|
||||||
|
|
||||||
|
expect(thing.value).to eq true
|
||||||
|
end
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
[source](https://makandracards.com/makandra/46189-how-to-rails-cache-for-individual-rspec-tests)
|
||||||
Reference in New Issue
Block a user