Rails 操作缓存 RSpec 测试失败

Tho*_*mas 5 rspec ruby-on-rails action-caching

我有一个规范,用于在禁用缓存和启用缓存时测试操作缓存。看起来测试执行的顺序会影响它们是否通过。

it "should not cache the index page when we're not caching" do
    ActionController::Base.perform_caching = false
    HomeController.caches_action :index
    Rails.cache.clear
    ActionController::Base.cache_store.exist?(:index_cache_path).should be_false
    get :index
    ActionController::Base.cache_store.exist?(:index_cache_path).should be_false
end

it "should cache the index page when we're caching" do
    ActionController::Base.perform_caching = true
    HomeController.caches_action :index
    Rails.cache.clear
    ActionController::Base.cache_store.exist?(:index_cache_path).should be_false
    get :index
    ActionController::Base.cache_store.exist?(:index_cache_path).should be_true
end
Run Code Online (Sandbox Code Playgroud)

当按上述顺序运行测试时,最后一个测试会失败,因为最后一个期望中不存在cache_store。我很困惑为什么无缓存测试会影响缓存测试。有谁知道出了什么问题吗?

Ann*_*rom 1

如果您将spec_helper.rb随机测试顺序变为true,那么这是有意义的,因为您没有取消“ActionController::Base.perform_caching = false”设置。

编写缓存测试的推荐方法是执行 before(:each) 和 after(:each) 来打开和关闭缓存设置。

由于您正在测试这些设置,因此如果您打开它,请记住在测试结束之前将其关闭,反之亦然。您的测试将更加原子化。