Joh*_*ash 6 caching rspec ruby-on-rails
这是我的Tag模型,我不知道如何测试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
Run Code Online (Sandbox Code Playgroud)
你知道怎么测试吗?
嗯,首先,你不应该真正测试框架.Rails的缓存测试表面上可以为您提供.也就是说,看看这个答案,你可以使用一个小帮手.您的测试看起来像是这样的:
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
Run Code Online (Sandbox Code Playgroud)
这实际上并没有检查缓存机制 - 只是#fetch没有调用块.它很脆弱并且与获取块的实现相关联,因此要注意它将成为维护债务.
| 归档时间: |
|
| 查看次数: |
10465 次 |
| 最近记录: |