Ste*_*han 18 testing caching ruby-on-rails ruby-on-rails-3
通常,我希望我的功能测试不执行动作缓存.轨道似乎是在我身边,默认为config.action_controller.perform_caching = false在environment/test.rb.这导致正常的功能测试没有测试缓存.
那么我如何在Rails 3中测试缓存.
这个线程中提出的解决方案似乎相当hacky或者对Rails 2: 如何在rails中的功能测试中启用页面缓存?
我想做的事情如下:
test "caching of index method" do
with_caching do
get :index
assert_template 'index'
get :index
assert_template ''
end
end
Run Code Online (Sandbox Code Playgroud)
也许还有更好的方法来测试缓存是否被击中?
ros*_*sta 30
rspec的解决方案:
添加带有自定义元数据键的around块到您的配置.
RSpec.configure do |config|
config.around(:each, :caching) do |example|
caching = ActionController::Base.perform_caching
ActionController::Base.perform_caching = example.metadata[:caching]
example.run
Rails.cache.clear
ActionController::Base.perform_caching = caching
end
end
Run Code Online (Sandbox Code Playgroud)
需要缓存时添加元数据键.
describe "visit the homepage", :caching => true do
# test cached stuff
end
Run Code Online (Sandbox Code Playgroud)
rag*_*ggi 28
你最终可能会互相踩踏测试.您应该确保将其包装起来并将其重置为旧值.一个例子:
module ActionController::Testing::Caching
def with_caching(on = true)
caching = ActionController::Base.perform_caching
ActionController::Base.perform_caching = on
yield
ensure
ActionController::Base.perform_caching = caching
end
def without_caching(&block)
with_caching(false, &block)
end
end
Run Code Online (Sandbox Code Playgroud)
我还把它放到一个模块中,这样你就可以把它包含在你的测试类或父类中.
我的版本有效:
RSpec.configure do |config|
config.around(:each) do |example|
caching = ActionController::Base.perform_caching
ActionController::Base.perform_caching = example.metadata[:caching]
example.run
Rails.cache.clear
ActionController::Base.perform_caching = caching
end
end
Run Code Online (Sandbox Code Playgroud)
归功于罗斯蒂,但是
| 归档时间: |
|
| 查看次数: |
7585 次 |
| 最近记录: |