2011-05-03 37 views
1

我已經編寫了一個cron作業來更新後臺中的某些緩存值(而不是在用戶等待時執行該操作)。我有一個運行該cron作業的場景,然後讀取緩存以查看值是否設置正確。如何爲單個黃瓜場景啓用Rails緩存

的問題是,Rails.cache.read("key")正在恢復"Cache read: key\n"沒有價值,如果我調試和檢查Rails.cache我得到返回的ActiveSupport::Cache::BlackHoleStore - 不是一個好兆頭。

這使得課程的意義,因爲下面是包含在我cucumber.env

config.action_controller.perform_caching    = false 
require File.join(RAILS_ROOT, 'lib', 'black_hole_store.rb') 
config.cache_store = :black_hole_store 

我想是在運行時忽略這一點 - 我們對一個個場景,這是需要的唯一一個緩存活動。我試圖從調試器提示沒有任何運氣以下:

(rdb:1) ActionController::Base.perform_caching = true 
true 
(rdb:1) ActionController::Base.perform_caching 
true 
(rdb:1) Rails.cache 
#<ActiveSupport::Cache::BlackHoleStore:0x101b6dc60 @logger_off=false> 
(rdb:1) ActionController::Base.cache_store = :memory_store 
:memory_store 
(rdb:1) Rails.cache 
#<ActiveSupport::Cache::BlackHoleStore:0x101b6dc60 @logger_off=false> 

任何人都知道如何做到這一點?

回答

0

這似乎與我的問題有關/我的問題here。問題在於,在Rails初始化後,您無法更改cache_store。有一個在Rails初始化期間運行的緩存初始化程序。據我所知,你不能改變它初始化後。也許你可以模擬緩存讀/寫?

2

好吧,所以我最終得到了這個底部。

簡短的回答是Rails.cacheRAILS_CACHE的別名,而沒有Rails.cache=方法可以分配給RAILS_CACHE,如:

ActionController::Base.perform_caching = true 
ActionController::Base.cache_store = :memory_store 
RAILS_CACHE = ActionController::Base.cache_store 

你也許還做RAILS_CACHE = ActiveSupport::Cache.lookup_store(:memory_cache)但似乎有點髒我。

較長的答案是使用一個步驟來包裝其他步驟的表格,其中包含啓用並禁用緩存的代碼,以確保您不會因啓用緩存而中斷其他測試 - 這種錯誤令人討厭追查。

這看起來是這樣的:

When /^I do the following steps with caching enabled:$/ do |table| 
    old_perform_caching = ActionController::Base.perform_caching 
    old_action_controller_cache = ActionController::Base.cache_store 
    old_rails_cache = RAILS_CACHE 

    ActionController::Base.perform_caching = true 
    ActionController::Base.cache_store = :memory_store 
    RAILS_CACHE = ActionController::Base.cache_store 

    steps table.raw.flatten.join("\n") 

    ActionController::Base.perform_caching = old_perform_caching 
    ActionController::Base.cache_store = old_action_controller_cache 
    RAILS_CACHE = old_rails_cache 
end 

,並用它看起來是這樣的:

When I do the following steps with caching enabled:    
| When I run "rake cron:nightly"    | 
| Then the cache for "x" should return "6" | 
| And the cache for "y" should return "13" | 
| And the cache for "z" should return "800" | 

表中已經明顯在其他地方實施的步驟。

+1

另一種方法是標記的場景(S)你想用@cache緩存運行。然後,您可以實現邏輯以在場景之前啓用緩存,然後在env.rb文件中禁用前塊和後塊。 – AlistairH 2011-05-05 10:03:09

2

試試這個...標籤您的場景與@enable_caching和這些掛鉤添加到您的support/env.rb文件:

Before '@enable_caching' do 
    ActionController::Base.perform_caching = true 
end 

After '@enable_caching' do 
    ActionController::Base.perform_caching = false 
end