2011-11-09 49 views

回答

16

要引發異常,您可以定義一個類來處理本地化錯誤。

class TestExceptionLocalizationHandler 
    def call(exception, locale, key, options) 
    raise exception.to_exception 
    end 
end 

然後你把它連接到所需的測試例

I18n.exception_handler = TestExceptionLocalizationHandler.new 

這樣你引發的異常。我不知道如何提高失敗率(以失敗告終)以取得更好的結果。

+0

太棒了,這正是我要找的。 –

+1

方法體內的「raise exception.message」會給你缺少翻譯的密鑰 – jankubr

+3

因爲處理程序只需要響應'#call',所以你可以使用lambda代替。 – fphilipe

8

我已經創建了這個初始化程序到raise一個異常 - 參數已通過,因此您將知道哪個i18n鍵已丟失!

# only for test 
if Rails.env.test? 

    # raises exception when there is a wrong/no i18n key 
    module I18n 
    class JustRaiseExceptionHandler < ExceptionHandler 
     def call(exception, locale, key, options) 
     if exception.is_a?(MissingTranslation) 
      raise exception.to_exception 
     else 
      super 
     end 
     end 
    end 
    end 

    I18n.exception_handler = I18n::JustRaiseExceptionHandler.new 

end 

Source

+0

從Rails 4.1.0開始,有一個簡單的方法可以做到這一點。看到我的答案。 – GMA

12

鐵軌4.1.0的,還有比現在4歲回答這個問題更好的解決方案:將下面的行添加到您的配置文件:

config.action_view.raise_on_missing_translations = true 

我只想在test環境中設置此項,但您可能也想將其設置爲development。我強烈建議不要在production中將其設置爲true。

+9

警告:這將在視圖和幫助程序中引發翻譯缺失錯誤** only **。 –

7

的Rails 4.1+

爲了提高國際化翻譯失蹤例外,你需要件事:

1)初始化config/initializers/i18n_force_exceptions.rb

module I18n 
    class ForceMissingTranslationsHandler < ExceptionHandler 
    def call(exception, locale, key, options) 
     if Rails.env.test? 
     raise exception.to_exception 
     else 
     super 
     end 
    end 
    end 
end 

I18n.exception_handler = I18n::ForceMissingTranslationsHandler.new 

2)config/environments/test.rb一個配置設置(和其他需要的環境):

config.action_view.raise_on_missing_translations = true 

注意:除了異常處理程序之外,還需要配置設置,因爲rails在其視圖中將調用包裝爲I18n.translate,助手阻止異常觸發。