首页 > 解决方案 > Rails.cache.fetch 在测试中产生错误

问题描述

ActionView::Template::Error: RSpec::Mocks::Double#marshal_dump returned same class instance在运行涉及Rails.cache.fetch. 在我的 config/environments/test.rb 我用这个禁用缓存(我认为):

config.cache_store = :null_store
config.action_controller.perform_caching = false

我的缓存方法需要一个过程并执行此操作

def use_cached(evaluate_value_proc, key, cache_options)
  Rails.cache.fetch(key, cache_options) do
    evaluate_value_proc.call
  end
end

在测试中,我希望缓存会丢失,并且块会被再次调用。这里发生了什么?

谢谢

标签: ruby-on-railscachingrspec

解决方案


我通过模拟返回的exist?方法来测试这些情况,以便该方法将调用memory_storefalsefetchblock

allow(Rails).to receive(:cache).and_return(ActiveSupport::Cache.lookup_store(:memory_store))
allow_any_instance_of(ActiveSupport::Cache::MemoryStore).to receive(:exist?).and_return(false)

推荐阅读