2011-02-09 202 views
3

假設我有一個包含許多之前過濾器的控制器。在控制器測試中,代碼永遠不會進入#create方法,儘管在規範中我做了post:create。在我的情況下,它是如何在rspec控制器測試期間登錄rails控制器過濾器

的before_filter:user_signed_in

沒有驗證,但測試日誌沒有表明這讓我不得不弄清楚通過依次打開/關閉所有過濾器。是否有可能讓Rails做一些詳細的日誌記錄,因爲它依次處理每個過濾器並將其輸出到測試日誌中?

回答

5

下面是我已經解決了同樣的問題。我確信下面的代碼仍然可以改進很多,並可能將其放入它自己的模塊中。改進的惠康。

你需要把下面的代碼放到頂部ActionController的,這通常是ApplicationController中或任何控制器是你需要跟蹤:

 
class ApplicationController < ActionController::Base 

    def self.before_filter_with_logging(*arguments, &block) 
    filters, conditions = 
     ActionController::Filters::FilterChain.extract_options(arguments, &block) 
    filter_method_names = filters.map { |fm| fm.to_s }.join(', ') 
    logger.info "Setting up before_filter to #{filter_method_names}" 

    filter_methods_with_logging = 
     filters.map { |fm| (fm.to_s + "_with_logging").to_sym } 

    filters.each { |fm| 
     define_method((fm.to_s + "_with_logging").to_sym) { |*args| 
     logger.info "Calling before_filter #{fm}" 

     if args.empty? 
      send fm 
     else 
      send fm, args 
     end 
     } 
    } 
    before_filter_without_logging(filter_methods_with_logging, &block) 
    end 

    class << self 
    alias_method_chain :before_filter, :logging 
    end 

    before_filter :your_first_before_filter 

托馬什Pospíšek

+0

這是否適用於Rails 3? – Sunny 2011-10-14 18:44:27

0

我沒有看到,爲什麼logger.info ":user_signed_in called"在該方法內不應該工作。你甚至可以做puts ":user_signed_in called",它直接在rspec的輸出之間打印該行。不會很漂亮,但它可能比讀取整個test.log文件更容易。

+1

我想你錯過的目的的問題。我想避免搜索每個過濾器的源代碼並在那裏插入Rails.logger命令。我希望軌道中可能存在一些鉤子以允許跟蹤回調序列。 – bradgonesurfing 2011-02-13 04:03:19