Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optionally testing caching in Rails 3 functional tests

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?

like image 913
Stephan Avatar asked Feb 17 '11 23:02

Stephan


People also ask

How can you implement caching in Rails?

You can create your own custom cache store by simply extending ActiveSupport::Cache::Store and implementing the appropriate methods. This way, you can swap in any number of caching technologies into your Rails application. To use a custom cache store, simply set the cache store to a new instance of your custom class.

How do I use Redis cache Rails?

To use Redis as a Rails cache store, use a dedicated cache instance that's set up as an LRU (Last Recently Used) cache instead of pointing the store at your existing Redis server, to make sure entries are dropped from the store when it reaches its maximum size.

Where is cache stored Rails?

Page caches are always stored on disk. Rails 2.1 and above provide ActiveSupport::Cache::Store which can be used to cache strings. Some cache store implementations, like MemoryStore, are able to cache arbitrary Ruby objects, but don't count on every cache store to be able to do that.

What are view caches?

View caching in Ruby on Rails is taking the HTML that a view generates and storing it for later.


1 Answers

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:

module ActionController::Testing::Caching
  def with_caching(on = true)
    caching = ActionController::Base.perform_caching
    ActionController::Base.perform_caching = on
    yield
  ensure
    ActionController::Base.perform_caching = caching
  end

  def without_caching(&block)
    with_caching(false, &block)
  end
end

I've also put this into a module so you can just include this in your test class or parent class.

like image 173
raggi Avatar answered Oct 12 '22 05:10

raggi