Rspecで特定のケースでは、cache_storeを変更したい場合があったのでその対応について残しておきます。
Rails.cacheをmockする
以下のようにActiveSupport::Cache.lookup_storeでRails.cacheモックすることでcache_storeを変更できます。
describe 'キャッシュストアを変更してテスト' do
let(:memory_store) { ActiveSupport::Cache.lookup_store(:memory_store) }
before(:each) { allow(Rails).to receive(:cache).and_return(memory_store) }
after(:each) { Rails.cache.clear }
it 'hogehoge' do
...
end
end
上の例では、 :memory_store
を設定していますが、 :null_store
、 :redis_store
など必要に応じて変更することができます。
metadataで設定を切り替えれるようにする
実際のプロジェクトで使う場合は毎回sotreの変更処理を書くのは手間なのでrails_helper.rbなどに以下のようにmetadataの設定のみで使えるようにするのが良いと思います。
rails_helper.rb
# 特定のキャッシュストアを使用したい場合に「chache_type: :memory_store」のように
# metadataを追加することで、そのテストケースのキャッシュストアを変更する。
config.around :each do |example|
if example.metadata[:chache_type].present?
old_store = Rails.cache
chache_store = ActiveSupport::Cache.lookup_store(example.metadata[:chache_type])
Rails.cache = chache_store
example.run
Rails.cache.clear rescue nil
Rails.cache = old_store
else
example.run
end
end
hoge_spec.rb
describe 'キャッシュストアを変更してテスト', chache_type: :memory_store do
it 'hogehoge' do
...
end
end
参考