2013-04-22 51 views
5

這是我的Tag模型,我不知道如何測試Rails.cache功能。我該如何測試rails緩存功能

class Tag < ActiveRecord::Base 
    class << self 
    def all_cached 
     Rails.cache.fetch("tags.all", :expires_in => 3.hours) do 
     Tag.order('name asc').to_a 
     end 
    end 
    def find_cached(id) 
     Rails.cache.fetch("tags/#{id}", :expires_in => 3.hours) do 
     Tag.find(id) 
     end 
    end 
    end 

    attr_accessible :name 
    has_friendly_id :name, :use_slug => true, :approximate_ascii => true 
    has_many :taggings #, :dependent => :destroy 
    has_many :projects, :through => :taggings 
end 

你知道怎麼會被測試嗎?

回答

7

嗯,首先,你不應該真的在測試框架。 Rails的緩存測試表面上覆蓋了你。也就是說,見this answer你可以使用一個小助手。那麼你的測試將類似於:

describe Tag do 
    describe "::all_cached" do 
    around {|ex| with_caching { ex.run } } 
    before { Rails.cache.clear } 

    context "given that the cache is unpopulated" do 
     it "does a database lookup" do 
     Tag.should_receive(:order).once.and_return(["tag"]) 
     Tag.all_cached.should == ["tag"] 
     end 
    end 

    context "given that the cache is populated" do 
     let!(:first_hit) { Tag.all_cached } 

     it "does a cache lookup" do 
     before do 
      Tag.should_not_receive(:order) 
      Tag.all_cached.should == first_hit 
     end 
     end 
    end 
    end 
end 

這並不實際檢查緩存機制 - 剛纔說的#fetch塊不被調用。它很脆弱,並與獲取塊的實現有關,所以要小心,因爲它會成爲維護債務。

+1

你在測試環境中使用哪個緩存存儲?你有test.env嗎? '''config.cache_store =:memory_store''' – knagode 2016-12-23 15:53:57

+1

我認爲測試框架完全可以確認它按我理解的方式工作。文檔可能不清楚,或者我可能不完全確定我的理解。與TDD一樣,編寫測試用例的行爲可以幫助我明確我想要達到的目標。 – 2017-09-22 18:09:39