2013-04-22 2 views
5

이것은 내 태그 모델이며 Rails.cache 기능을 테스트하는 방법을 모르겠습니다.레일 캐쉬 기능을 테스트하는 방법은 무엇입니까

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

+1

프레임 워크를 테스트하는 것이 그것이 내가 이해하는 방식으로 작동한다는 것을 확인하는 것은 완벽하다고 생각합니다. 문서가 나에게 분명하지 않을 수도 있고, 아니면 내 이해를 완전히 확신하지 못할 수도 있습니다. TDD의 경우와 마찬가지로 테스트 사례를 작성하는 것만으로도 내가 달성하고자하는 것을 명확하게 설명 할 수 있습니다. –

관련 문제