这是我的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
你知道它怎么能被测试?
答案 0 :(得分: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 :(得分:0)
我同意@chris-heald's answer。为了减少测试的难度,您可以通过以下方式更改代码:
"version": "0.2.0",
"configurations": [
{
"type": "firefox",
"request": "launch",
"reAttach": true,
"name": "Launch localhost",
"url": "http://localhost:8080/dibichain/",
"webRoot": "${workspaceFolder}/client",
},
并通过以下方式对其进行测试:
def self.all_cached
Rails.cache.fetch('tags.all', expires_in: 3.hours) do
all_uncached
end
end
def self.all_uncached
Tag.order('name asc').to_a
end