Rails fragment cache testing with RSpec

Let me first say that in this answer, you may get more sympathy then fact. I've been struggling with these same issues. While I was able to get reproducible results for a particular test, I found that the results varied according to whether or not I ran one versus multiple specs, and within or without spork. Sigh.

In the end, I found that 99.9% of my issues disappeared if I simply enabled caching in my test.rb file. That might sound odd, but after some thought it was "correct" for my application. The great majority of my tests are not at the view/request layer, and for the few that are, doesn't it make sense to test under the same configurations that the user views?

While I was wrestling with this, I wrote a blog post that contains some useful test helpers for testing caching. You might find it useful.


Here is what I've used in my specs with caching enabled in my config/environments/test.rb

require 'spec_helper'
include ActionController::Caching::Fragments

describe 'something/index.html.erb' do
  before(:each) do 
    Rails.cache.clear
    render
  end
  it 'should cache my fragment example' do
    cached_fragment = Rails.cache.read(fragment_cache_key(['x', 'y', 'z']))
    cached_fragment.should have_selector("h1")
  end
end