Hirurg103
Hirurg103

Reputation: 4963

How to test cache expiration in rails with rspec?

I want to test cache expiration in a Rails view. The view looks like this:

# products/index.html.erb
<% @products.each do |product| %>
  <% cache product do %>
    <%= render product %>
  <% end %>
<% end %>

Product's partial renders owner, items, category, tags, etc. that are linked to the product. I expire cache for a product every time the product or an object linked to it gets updated

There are few ways to test cache expiration for a product:

  1. Model spec: test that product's cache_version is being changed when updating the product or a linked object
  2. View spec: test that new properties are rendered in the product's index template
  3. Request spec: test that new properties are returned in the response body

cache_version for the Product model looks like this:

def cache_version
  [touched_at, updated_at].compact.map(&:utc).max.to_s(:usec)
end

The problem with #1 is that somebody could change the product partial so it won't use cache_version method. For example, after upgrade from rails 5.1 to 5.2 caching mechanism has been changed to use cache_version instead of cache_key

What about if somebody changes

Which way would you choose to test cache expiration and why?

Upvotes: 0

Views: 563

Answers (0)

Related Questions