Rails action caching RSpec test fails

2k Views Asked by At

I have a spec that tests action caching when caching is disabled and when caching is enabled. It seems like the order of test execution affects whether they pass or not.

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

When tests are run in the above order the last test fails because the cache_store does not exist in the last expectation. I'm stumped on why the no caching test is affecting the caching test. Does anyone know what is wrong?

2

There are 2 best solutions below

0
On

Make sure that you have:

config.action_controller.perform_caching = true

In environment/test.rb.

Else - i noticed super strange thing. Caching worked when I run only requests tests (spring rspec spec/requests describe '..' type: :request), but same tests failed if I run everything with rspec spec.

0
On

If you have spec_helper.rb random test order turned to true, it makes sense since you're not un-doing your "ActionController::Base.perform_caching = false" setting.

The recommended way to write caching tests is to do a before(:each) and after(:each) setting the caching settings on and off.

Since you're testing these settings, if you turn it on, remember to turn it off before the end of the test, and vice-versa. Your tests will be more atomic.