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

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

所以在我的应用程序中,我可以禁用所有测试的缓存,这将是理想的,但显然有许多遗留测试依赖于缓存的功能。有没有办法为单个 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

关于ruby-on-rails - 单个测试的 Rails/RSpec 切换缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31929514/

相关文章:

ruby-on-rails - 使用 Guard 和 Spork 重新加载 RSpec 共享示例

ruby-on-rails - 如何一步将Rails中的X个月转换为Y天?

ruby-on-rails - 错误原始错误:未安装ImageMagick/GraphicsMagick

ruby-on-rails - 从javascript触发茧add_association

mysql - 如何将 Rails 应用程序迁移到不同的托管服务提供商

rspec - 期望下拉菜单有内容

ruby-on-rails - RubyMine 6.3 中 RSpec 文件夹上下文菜单中的测试

ruby-on-rails - RailsTutorial - 第 8.4.3 章 - 在集成测试中添加用户后未清除测试数据库

html - 是否可以在没有任何 CSS 的情况下设置样式?(仅使用类似应用程序的 photoshop)

mysql - Rails db:seed 出现 ActiveRecord::RecordInvalid 错误:验证失败:类别必须存在