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

ruby-on-rails – 用于单个测试的Rails / RSpec切换缓存

发布时间:2020-12-16 23:07:06 所属栏目:百科 来源:网络整理
导读:因此,在我的应用程序中,我可以禁用所有测试的缓存,这将是理想的,但显然有许多遗留测试依赖于缓存功能.有没有办法为单个RSpec测试启用Rails缓存? 就像是: before(:each) do @cache_setting = Rails.cache.null_cache Rails.cache.null_cache = trueendafter
因此,在我的应用程序中,我可以禁用所有测试的缓存,这将是理想的,但显然有许多遗留测试依赖于缓存功能.有没有办法为单个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

解决方法

在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

(编辑:李大同)

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

    推荐文章
      热点阅读