Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test rails fragment cacheing with rSpec?

I'm using fragment caches pretty extensively and have ran into a few gotchas where unexpected objects got caught in the cache and/or the fragment didn't expire as originally planned.

I think this would be a prime candidate for request specs but am not sure of:

  1. What would need to be done to simulate a scenario where a cache is triggered (efficiently).
  2. What adjustments would need to be done in the test environment to allow for cacheing.
  3. Would the cache persist across multiple specs or would rspec automatically discard the cache between each spec?
  4. Most importantly, is there a method to determine if the cache was actually served?
like image 204
Jim Jeffers Avatar asked Sep 05 '25 09:09

Jim Jeffers


1 Answers

  1. Issuing two requests in the same test case would be the most realistic way.
  2. You would need to enable caching in your test environment, by default it's turned on only in production. Ideally not every test suite needs to have caching enabled so you'd need to flip this on/off before/after a suite. See this question: Optionally testing caching in Rails 3 functional tests
  3. It depends on your storage layer for cache fragments, but Rails.cache.clear should be smart enough. I don't think there's any case where you would want the cache to persist across specs since pollution will make things confusing.
  4. If your fragment makes a database call, stub the database connection in your tests, returning a fake result the first time, and raising an exception the second time. This can be generalized to other slow calls (such as a network request).
like image 118
bdon Avatar answered Sep 08 '25 10:09

bdon