how can I test rails cache feature
Well, first, you shouldn't really be testing the framework. Rails' caching tests ostensibly cover that for you. That said, see this answer for a little helper you can use. Your tests would then look something like:
describe Tag do
describe "::all_cached" do
around {|ex| with_caching { ex.run } }
before { Rails.cache.clear }
context "given that the cache is unpopulated" do
it "does a database lookup" do
Tag.should_receive(:order).once.and_return(["tag"])
Tag.all_cached.should == ["tag"]
end
end
context "given that the cache is populated" do
let!(:first_hit) { Tag.all_cached }
it "does a cache lookup" do
before do
Tag.should_not_receive(:order)
Tag.all_cached.should == first_hit
end
end
end
end
end
This doesn't actually check the caching mechanism - just that the #fetch
block isn't invoked. It's brittle and tied to the implementation of the fetch block, so beware that as it will become maintenance debt.