Johnny Cash
Johnny Cash

Reputation: 5147

rails rspec testing cache method

This is my user model and I don't know how can I write test for active_and_approved_creative_count cache test.

User.rb

class User < ActiveRecord::Base
  class << self
    def active_and_approved_creative_count
      Rails.cache.fetch('active_and_approved_creative_count', :expires_in => 30.minutes) do
        User.active_and_approved_creative.count
      end
    end
   ...
   scope :active_and_approved_creative ,where("user_type = ? AND (membership_cancelled IS NULL OR membership_cancelled = false)", :approved_creative)
end

Upvotes: 1

Views: 1501

Answers (1)

Brad Werth
Brad Werth

Reputation: 17647

You could probably:

  1. access active_and_approved_creative_count to prime the cache and verify the initial value
  2. perform an action that will increment the count
  3. Use TimeCop to move up 29 minutes
  4. Verify that the count is still the cached value
  5. Travel up another minute or two
  6. Verify that the count has now incremented

One might argue that this is testing the Rails internals unnecessarily, consider whether simply performing step #1 may be enough.

Upvotes: 1

Related Questions