is Rails.cache purged between tests?

2020-02-17 06:07发布

We cache id/path mapping using Rails.cache in a Rails 3.2 app. On some machines it works OK, but on the others values are wrong. The cause is hard to track so I have some questions about the Rails.cache itself. Is it purged between tests? Is it possible that values cached in development mode is used in test mode? If it's not purged, how could I do it before running specs?

My cache store is configuration is:

#in: config/environments/development.rb
config.cache_store = :memory_store, {:size => 64.megabytes}

#in: config/environments/production.rb
# config.cache_store = :mem_cache_store

2条回答
2楼-- · 2020-02-17 06:44

Add:

before(:all) do
  Rails.cache.clear
end

to have the cache cleared before each spec file is run.

Add:

before(:each) do
  Rails.cache.clear
end

to have the cache cleared before each spec.

You can put this inside spec/spec_helper.rb within the RSpec.configure block to have it applied globally (recommended over scattering it per spec file or case).

RSpec by default does not clear that cache automatically.

查看更多
Rolldiameter
3楼-- · 2020-02-17 06:47

A more efficient (and easier) method is to set the test environment's cache to use NullStore:

# config/environments/test.rb:
config.cache_store = :null_store

The NullStore ensures that nothing will ever be cached.

For instance in the code below, it will always fall through to the block and return the current time:

Rails.cache.fetch('time') { Time.now }

Also see the Rails Caching guide: http://guides.rubyonrails.org/caching_with_rails.html#activesupport-cache-nullstore

查看更多
登录 后发表回答