By default, caching in a Rails application is only enabled in a production environment. To be able to test application logic for caching there are at least two immediate solutions, being (1) enable caching for all tests and (2) enable cache for individual tests. For this article, we shall consider the latter.

Assuming the default caching configuration for test environment

config.action_controller.perform_caching = false
config.cache_store = :null_store

the strategy to enable it for individual tests consists of stubbing Rails.cache and clearing it before each example, like so:

RSpec.describe User, type: :model do
  let(:memory_store) { ActiveSupport::Cache.lookup_store(:memory_store) }
  let(:cache) { Rails.cache }

  before do
    allow(Rails).to receive(:cache).and_return(memory_store)
    Rails.cache.clear
  end

  it 'fetches last_activity_at from cache' do
    user = create(:user)
    cache_key = "user:last_activity_at:#{user.id}"

    expect(Rails.cache.exist?(cache_key)).to be_falsy

    now = Time.now
    Rails.cache.write(cache_key, now)
    expect(Rails.cache.read(cache_key)).to eq(now)
  end
end