Skip to content
Edit this page View source of this page

Test the cache

Because the cache is a container component with a configurable store, you can test cached code with an in-memory store and swap in your own cache instance for one object. This guide shows how to set up the cache in tests, test code that caches, control time, and test a custom store.

The examples use RSpec and the clock page from Cache your first view fragment.

Set up the cache in tests

  1. In config/providers/cache.rb, select the memory store for the test environment:

    # config/providers/cache.rb
    require "mankai/cache"
    
    Hanami.app.register_provider(:cache, from: :mankai_cache) do
      configure do |config|
        config.store = Hanami.env?(:test) ? :memory : :file
        config.expires_in = 3600
      end
    end
    
  2. Create spec/support/cache.rb to clear the cache before each example:

    # spec/support/cache.rb
    RSpec.configure do |config|
      config.before { Hanami.app["cache"].clear }
    end
    

    Hanami's generated spec/spec_helper.rb loads every file in spec/support.

Each test process starts with an empty memory store, and clearing it before each example keeps one example from reading another's entries. Unlike the null store, the memory store keeps values, so a test can check that a value was stored and reused. Don't use the null store in tests: tests that check stored values fail with it.

Test that a value is reused

To test the cache's behavior directly, get the cache from the app container and call it:

# spec/cache_spec.rb
RSpec.describe "the cache" do
  subject(:cache) { Hanami.app["cache"] }

  it "runs the block on a miss and reuses the value on a hit" do
    calls = 0
    compute = ->(_key) { calls += 1; "value" }

    expect(cache.fetch("key", expires_in: 60, &compute)).to eq("value")
    expect(cache.fetch("key", expires_in: 60, &compute)).to eq("value")
    expect(calls).to eq(1)
  end

  it "recomputes after delete" do
    cache.write("key", "value")
    cache.delete("key")
    expect(cache.fetch("key") { "new" }).to eq("new")
  end
end

Test an action that caches

Use a request spec and check the observable result. To check that the action cached a value, look in the cache after the request. The request and the spec share the same "cache" component, so the spec sees what the action wrote:

# spec/requests/clock_spec.rb
RSpec.describe "GET /clock", type: :request do
  it "caches the report" do
    get "/clock"

    expect(last_response).to be_ok
    expect(Hanami.app["cache"].exist?("clock/report")).to be(true)
  end
end

Use the same key that the action uses. For example, route params are strings, so an action that caches ["books", request.params[:id]] for /books/1 stores the key ["books", "1"].

Test the view helper

To test a cached view fragment, render the page twice and compare the cached part. The following spec checks that the clock page's cached time stays the same while the rendered time changes:

# spec/requests/clock_fragment_spec.rb
RSpec.describe "Clock fragment", type: :request do
  it "caches part of the page" do
    get "/clock"
    cached = last_response.body[/Cached at ([\d:.]+)/, 1]

    sleep 0.01
    get "/clock"
    expect(last_response.body[/Cached at ([\d:.]+)/, 1]).to eq(cached)
    expect(last_response.body[/Rendered at ([\d:.]+)/, 1]).not_to eq(cached)
  end
end

Test expiry without sleeping

The cache reads the current time from a clock. To control time in a test, create a cache with a clock that you can move, and pass it to the object under test. The clock is any object whose call returns a Time.

Hanami components accept their dependencies as keyword arguments. Passing cache: replaces the app's cache for that one object. The following class caches a count for five minutes:

# app/book_stats.rb
module Bookshelf
  class BookStats
    include Deps["cache", "repos.book_repo"]

    def count
      cache.fetch("books/count", expires_in: 300) { book_repo.count }
    end
  end
end

The following spec moves the clock forward by five minutes and checks that the count is recomputed:

# spec/book_stats_spec.rb
RSpec.describe Bookshelf::BookStats do
  subject(:stats) { described_class.new(cache: cache, book_repo: book_repo) }

  let(:clock) { Struct.new(:now) { def call = now }.new(Time.utc(2026, 1, 1, 12)) }
  let(:cache) { Mankai::Cache.new(clock: clock) }
  let(:book_repo) { double(:book_repo, count: 3) }

  it "counts again after five minutes" do
    expect(stats.count).to eq(3)

    allow(book_repo).to receive(:count).and_return(4)
    expect(stats.count).to eq(3)

    clock.now += 300
    expect(stats.count).to eq(4)
  end
end

Mankai::Cache.new uses a memory store by default, so this cache is separate from the app's cache.

Test a custom store

If you write a custom store, check it against the shared examples that mankai-cache provides:

require "mankai/cache/testing/store_examples"

RSpec.describe MyStore do
  subject(:store) { MyStore.new }

  it_behaves_like "a mankai-cache store"
end

The examples cover reads, writes, deletes, multi-key operations, updates, clearing, and cleanup. If your store's cleanup doesn't delete entries by their expiry time, pass cleanup: false: it_behaves_like "a mankai-cache store", cleanup: false.

What's next