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

标签 ruby-on-rails caching rspec

这是我的标签模型,我不知道如何测试 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作为一个小 helper ,你可以使用。您的测试将如下所示:

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块没有被调用。它很脆弱并且与 fetch 块的实现相关联,所以要小心,因为它会成为维护债务。

关于ruby-on-rails - 如何测试 Rails 缓存功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16156862/

相关文章:

django - 在 Django 中缓存模型实例(对象级缓存)的最佳框架/可重用应用程序是什么?

Python Flask 强制重新加载缓存的 JS 文件

ruby - 我如何获得 rspec 的整个错误回溯?

ruby - 在 rspec 中 stub require 语句?

ruby-on-rails - Rails 路线/名称而不是/用户/:id

css - Rails - 在某些情况下使用 CSS

c# - 我如何在 ASP.NET MVC 3.0 项目中以正确的方式进行缓存?

ruby-on-rails - Rspec 没有看到我的模型类。未初始化常量错误

ruby-on-rails - rails 4、postgres 和数组

ruby-on-rails - 在 Rails 中存储到数据库之前透明地压缩属性