如何测试Rails缓存功能 [英] how can I test rails cache feature

查看:55
本文介绍了如何测试Rails缓存功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的Tag模型,我不知道如何测试Rails.cache功能。

This is my Tag model and I don't know how can I test Rails.cache feature.

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

您知道如何对其进行测试吗?

Do you know how can it will be tested ?

推荐答案

首先,您不应该真正在测试框架。 Rails的缓存测试表面上可以满足您的要求。也就是说,请参见此答案,以获取一些帮助用。然后,您的测试将类似于:

Well, first, you shouldn't really be testing the framework. Rails' caching tests ostensibly cover that for you. That said, see this answer for a little helper you can use. Your tests would then look something like:

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 块不被调用。它很脆弱,并且与提取块的实现紧密相关,因此请当心,因为它将成为维护债务。

This doesn't actually check the caching mechanism - just that the #fetch block isn't invoked. It's brittle and tied to the implementation of the fetch block, so beware that as it will become maintenance debt.

这篇关于如何测试Rails缓存功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆