Generally, I want my functional tests to not perform action caching. Rails seems to be on my side, defaulting to config.action_controller.perform_caching = false
in environment/test.rb
. This leads to normal functional tests not testing the caching.
So how do I test caching in Rails 3.
The solutions proposed in this thread seem rather hacky or taylored towards Rails 2: How to enable page caching in a functional test in rails?
I want to do something like:
test "caching of index method" do
with_caching do
get :index
assert_template 'index'
get :index
assert_template ''
end
end
Maybe there is also a better way of testing that the cache was hit?
A solution for rspec:
Add an around block with a custom metadata key to your configuration.
Add the metadata key when caching is needed.
Here is my current solution to the problem: In
environment/test.rb
I setAlso, I am monkey patching
Test::Unit::TestCase
as follows:This allows me to write the following tests:
It's not perfect, but works for now. I am still interested in better ideas!!
This is not an answer, rather a few limitations to be aware of which don't fit in a comment.
All the (amazing) answers relying on
ActionController::Base.perform_caching
will not work for low-level caching (cf this answer). The only option you have is the module independentconfig.cache_store
setting that you set to:null_store
.As @viktor-trón said earlier setting the
cache_store
is not possible between tests, only at init.The cache is shared between environments for the default
cache_store
. As a result, (i) the cache should be cleared before testing if you fear stuff from your development session, (ii) running tests clears the cache of your other environments. However, your production environment should use something like themem_cache_store
or whatever else more suited for it, so it should be fine.From the two first points, it seems that testing for low-level caching is not possible as a per example basis.
My version that works:
Credit to Rossti, but
You're liable to end up with tests stomping on each other. You should wrap this up with ensure and reset it to old values appropriately. An example:
I've also put this into a module so you can just include this in your test class or parent class.