2011-02-04 38 views
10

我升級Rails的2至3的Rails應用程序(不是我寫的代碼)。 的(以及測試的代碼)使用早該和測試::單位,並廣泛使用的宏should_create和should_change。如何選擇性地靜音Rails 3棄用警告?

我從this discussion瞭解到,shoulda維護者想擺脫這兩種方法,但使用Test :: Unit的人沒有發現它是必要的(不確定我是否理解了整個討論)。

Anaway,有沒有辦法能夠選擇性地指定宏打開廢棄警告嗎?我已經從this posting知道,你完全可以通過設置關在瑞克測試輸出的廢棄警告:

ActiveSupport::Deprecation.silenced = true 
在您的測試環境文件

,我也知道,你可以把特定的代碼塊的塊,讓他們沉默:

ActiveSupport::Deprecation.silence do 
# no warnings for any use of deprecated methods here 
end 

後者是一種選擇,而是需要我去了所有的測試和封閉should_create宏在這樣一個塊。所以我想知道有一種方法可以完全消除一個配置設置的特定宏的警告?

回答

3

其實我還是老樣子有很多從其他代碼廢棄警告,那是在插件或我已經安裝了寶石。爲了避免大部分情況,我重寫了test_helper.rb中的Deprecation :: warn方法。因此,而不是上面的代碼中使用:

module ActiveSupport 
    module Deprecation 
    class << self 
     def warn(message = nil, callstack = caller) 
     # modif pvh the following lines make sure no deprecation warnings are sent 
     # for code that is 
     # not by my but in some gem or plugin... 
     return if silenced || callstack.grep(/myrailsappname/).blank? 
     # return if silenced 
     deprecation_message(callstack, message).tap do |m| 
      behavior.each { |b| b.call(m, callstack) } 
     end 
     end 
    end 
    end 
end 

順便說一句,你需要與你的應用程序的名稱(它駐留在該文件夾的名稱),以取代myrailsappname。可能有更通用的方式來獲得該名稱,但我現在找不到它。

0

我想我已經發現了一個解決方案:在測試/ test_helper.rb中我重新打開該模塊並改寫宏定義具有相同的定義,但棄用警告註釋。可能有更優雅的方式來做到這一點,但...

# modif pvh DEPREC 
# reopen the module and silence the deprecation statement to avoid 
# having my results overflown by these deprecation warnings... 
module Shoulda # :nodoc: 
    module Macros 
    def should_create(class_name) 
     ##::ActiveSupport::Deprecation.warn 
     should_change_record_count_of(class_name, 1, 'create') 
    end 
    end 
end 
6

老問題 - 但如果你有你想選擇忽略新的貶值:

ActiveSupport::Deprecation.behavior = lambda do |msg, stack| 
    unless /LIBRARY_NAME/ =~ msg 
    ActiveSupport::Deprecation::DEFAULT_BEHAVIORS[:stderr].call(msg,stack) # whichever handlers you want - this is the default 
    end 
end 

這是ActiveSupport 3

+2

仍然可以在ActiveSupport 4中使用。 – 2015-03-10 20:09:49

2

我可以推薦別的選擇嗎?

module ActiveSupport 
    class Deprecation 
    module Reporting 
     # Mute specific deprecation messages 
     def warn(message = nil, callstack = nil) 
     return if message.match(/Automatic updating of counter caches/) 

     super 
     end 
    end 
    end 
end