加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何测试rails缓存功能

发布时间:2020-12-17 03:31:09 所属栏目:百科 来源:网络整理
导读:这是我的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/#
这是我的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

你知道怎么测试吗?

解决方法

嗯,首先,你不应该真正测试框架. 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块.它很脆弱并且与获取块的实现相关联,因此要注意它将成为维护债务.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读