【问题标题】:rails test fails for testing custom cache storerails test 无法测试自定义缓存存储
【发布时间】:2018-06-13 01:18:27
【问题描述】:

在 Rails 4.2 中,我正在扩展 ActiveSupport::Cache::FileStore 以创建自己的备份值到数据库的内容。这是目前的样子:

class FileStoreWithDbBackup < ActiveSupport::Cache::FileStore

  def write(name, value, options = nil)
    super(name, value, options)
    Rails.logger.debug('write!')
    if options[:backup]
      backup = CacheBackup.find_or_create_by(name: name)
      backup.value = value
      if options[:expires_in]
        backup.expires = options[:expires_in].from_now
      end
      backup.save
    end
  end

end

当我从控制台使用它时,它似乎工作正常,但是当我在测试环境中尝试它时,超类功能工作(它缓存和恢复值)但数据库备份不起作用。我需要更改测试环境配置吗?

我尝试将config.action_controller.perform_caching 设置为true,但没有成功。

这是我的测试文件(使用 minitest-spec 语法):

require 'test_helper'
require 'file_store_with_db_backup'

describe FileStoreWithDbBackup do

  let(:store) {FileStoreWithDbBackup.new 'tmp/cache/'}
  let(:key) {'data key'}
  let(:payload) {'data value'}

  it 'caches data' do
    store.fetch(key){ payload }
    fetched = store.fetch(key) do
      fail('regenerating value')
    end
    _(fetched).must_equal payload
  end

  it 'backs up to db when asked' do
    store.fetch(key, expires_in: 1.day, backup: true) { payload }
    backup = CacheBackup.find_by_name key
    _(backup.value).must_equal payload
    _(backup.expires).must_be_close_to 1.day.from_now
  end

end

第一个测试通过,第二个测试在找不到CacheBackup时触底。

更新

当我在测试中直接调用write 方法时,它可以工作,但是如果商店的超类的fetch 方法没有找到密钥并且提供了一个块,它应该调用write 方法。这适用于 rails 控制台,但不适用于测试。

【问题讨论】:

    标签: ruby-on-rails unit-testing testing caching automated-tests


    【解决方案1】:

    我意识到缓存的内容(在这种情况下是存储在我的本地文件系统上的文件中)在测试之间被持久化,实际上,在测试套件的运行之间。

    缓存存储超类的 fetch 方法没有调用 write 方法,因为它正在缓存中查找条目。

    所以我有必要在每次测试之前使用测试文件中的before 方法清除缓存

    before do
      store.clear
    end
    

    【讨论】:

      猜你喜欢
      • 2017-07-17
      • 2013-05-04
      • 2021-10-23
      • 2015-07-16
      • 2016-07-08
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多