3

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?
Jim Jeffers
  • 17,572
  • 4
  • 41
  • 49
  • Could you clarify (1)? Would issuing a GET request not be a realistic simulation? – bdon Feb 19 '12 at 05:11
  • @bdon I guess what I'm asking is - would I need to fire at least 2 get requests for every 'cacheing spec' once to cache it, once to verify? Or is there a more efficient way? There might not be but I was wondering if there is or isn't. – Jim Jeffers Feb 19 '12 at 05:17
  • Even if there was another way to warm your caches, it seems like firing two requests would be the most realistic. A single request should not add much overhead to your test suite. – bdon Feb 19 '12 at 05:20
  • There is [a similar question](https://stackoverflow.com/questions/8482450/rails-fragment-cache-testing-with-rspec), I added [an example](https://stackoverflow.com/a/60167613/3676469) how I use rspec view specs to test cache expiration in rails views – Hirurg103 Feb 11 '20 at 12:46

1 Answers1

3
  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).
Community
  • 1
  • 1
bdon
  • 2,068
  • 17
  • 15