Ruby-on-rails Rails.cache 在测试之间清除了吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13309121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is Rails.cache purged between tests?
提问by mrzasa
We cache id/path mapping using Rails.cachein 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.cacheitself. 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?
我们Rails.cache在 Rails 3.2 应用程序中使用缓存 id/path 映射。在某些机器上它工作正常,但在其他机器上值是错误的。原因很难追踪,所以我对它Rails.cache本身有一些疑问。它在测试之间被清除了吗?在开发模式下缓存的值是否有可能在测试模式下使用?如果它没有被清除,我怎么能在运行规范之前做到这一点?
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
回答by jaustin
A more efficient (and easier) method is to set the test environment's cache to use NullStore:
一种更有效(也更简单)的方法是将测试环境的缓存设置为使用 NullStore:
# config/environments/test.rb:
config.cache_store = :null_store
The NullStore ensures that nothing will ever be cached.
NullStore 确保不会缓存任何内容。
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
另请参阅 Rails 缓存指南:http: //guides.rubyonrails.org/caching_with_rails.html#activesupport-cache-nullstore
回答by mrzasa
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.rbwithin the RSpec.configureblock to have it applied globally (recommended over scattering it per spec file or case).
你可以把这个里面spec/spec_helper.rb的内RSpec.configure块有它全局应用(建议在每个规格文件或情况下散播)。
RSpec by default does not clear that cache automatically.
默认情况下,RSpec 不会自动清除该缓存。

