【问题标题】:Rails/RSpec toggle cache for a single test用于单个测试的 Rails/RSpec 切换缓存
【发布时间】:2015-08-10 21:29:44
【问题描述】:

所以在我的应用程序中,我可以禁用所有测试的缓存,这将是理想的,但显然有许多遗留测试依赖于缓存的功能。有没有办法为单个 RSpec 测试启用 Rails 缓存?

类似:

before(:each) do
  @cache_setting = Rails.cache.null_cache
  Rails.cache.null_cache = true
end

after(:each) do
  Rails.cache.null_cache = @cache_setting
end

it 'does not hit the cache' do
  ...
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rspec rspec3


    【解决方案1】:

    spec_helper.rb

    RSpec.configure do |config|
      config.before(:example, disable_cache: true) do
        allow(Rails).to receive(:cache).and_return(ActiveSupport::Cache::NullStore.new)
      end
    
      config.after(:example, disable_cache: true) do
        allow(Rails).to receive(:cache).and_call_original
      end
    end
    

    xxx_spec.rb

    RSpec.describe "a group without matching metadata" do
      it "does not run the hook" do
         puts Rails.cache.class
      end
    
      it "runs the hook for a single example with matching metadata", disable_cache: true do
         puts Rails.cache.class
      end
    end
    

    https://www.relishapp.com/rspec/rspec-core/docs/hooks/filters

    【讨论】:

    • 谢谢,这正是我所需要的。我能够通过修改您的模拟以返回 ActiveSupport::Cache::MemoryStore.new 来启用缓存(而不是禁用)。
    猜你喜欢
    • 2013-05-04
    • 2013-01-06
    • 1970-01-01
    • 2012-03-09
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多