mercredi 3 janvier 2018

rails test fails for testing custom cache store

in Rails 4.2 I'm extending ActiveSupport::Cache::FileStore to make my own that backs up values to the database. This is what it looks like so far:

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

When I use it from the console it seems to work fine, but when I try it in the testing environment the superclass functionality works (it caches and restores values) but the database backup doesn't work. Is there something about the testing environment config that I need to change?

I tried setting config.action_controller.perform_caching to true but that didn't work.

Here is my test file (which uses minitest-spec syntax):

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

The first test passes, the second test bottoms out when it can't find the CacheBackup.

Aucun commentaire:

Enregistrer un commentaire