Skip to content

Instantly share code, notes, and snippets.

@goggin13
Last active December 10, 2015 20:38
Show Gist options
  • Save goggin13/4489750 to your computer and use it in GitHub Desktop.
Save goggin13/4489750 to your computer and use it in GitHub Desktop.
A demo of some code I wrote to ensure cached values were being flushed appropriately.
# in spec_helper.rb
# Verify that the cache_busters bust the cache of the given method.
#
# * method is the name of the method we are testing (for RSpec output)
# * cache_busters is a hash of labels => procs which should result in
# in the cache being flushed
#
# Please set these variables in specs which will be using this function:
# @cached_function : a proc which executes the code to populate the cache
# @key : a proc which returns the relevant cache key
# @args : an array which will be used as the arguments to each of the cache
# buster functions when they are called
def test_caching(method, cache_busters)
describe "caching -" do
before { @cached_function.call }
it "should get cached" do
Rails.cache.exist?(@key.call).should be_true
end
cache_busters.each do |label, f|
it "should flush the cache after #{label}" do
f.call(*@args)
Rails.cache.exist?(@key.call).should be_false
end
end
end
end
# Example spec, in any spec file
describe "attributed" do
before do
user = Factory(:user)
conversation = user.conversations.create!
@cached_function = -> { user.attributed }
@key = -> { user.get_cache_key(:attributed) }
@args = [conversation]
end
cache_busters = {
"deleting a participant" => ->(*args) {
args[0].participants[0].destroy
},
"creating a new participant" => ->(*args) {
args[0].participants.create!
},
"updating a participant" => ->(*args) {
args[0].participants[0].update_attributes! :username => "new name"
}
}
test_caching :attributed, cache_busters
end
# Runs the following specs...
# attributed caching - should get cached
# attributed caching - should flush the cache after creating a new participant
# attributed caching - should flush the cache after deleting a participant
# attributed caching - should flush the cache after updating a participant
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment