【发布时间】:2021-09-23 08:17:58
【问题描述】:
我正在尝试通过检查是否正在调用访问数据库的函数来测试我的应用中的缓存。
我的控制器:
class MyApp::MyController < MyApp::BaseController
def index
@cache_key = "testkeydd"
@current_time = Time.current
@data = Rails.cache.fetch(@cache_key, expires_in: 1.hour) do
get_from_database
end
end
def get_from_database
puts "============DATABASE HIT============"
Data.last(20)
end
end
我的规格:
describe MyApp::MyController, type: :controller do
let(:memory_store) { ActiveSupport::Cache.lookup_store(:memory_store) }
before :each do
allow(Rails).to receive(:cache).and_return(memory_store)
Rails.cache.clear
allow(controller).to receive(:get_from_database).and_call_original
end
describe 'GET /myroute' do
it 'hits the database after creating a new booking' do
get :index, format: :json #First request
expect(controller).to have_received(:get_from_database) #Passes
get :index, format: :json #Second request
expect(controller).not_to have_received(:get_from_database) #Fails
end
end
end
当我运行规范时,函数 get_from_database 仅在第一个请求时调用,而不是在第二个请求时调用。
您是否希望测试通过。然而expect(controller).not_to have_received(:get_from_database) 失败:
expected: 0 times with any arguments
received: 1 time
【问题讨论】:
-
测试环境中是否启用了 Rails 缓存?
-
@SampatBadhe
memory_store
标签: ruby-on-rails caching rspec