Rails:如何提高I18n转换是在测试环境中缺少exception

我希望Rails在测试环境中缺少I18n转换时引发exception(而不是渲染文本’translation missing’)。 有没有一种简单的方法来实现这一目标?

要引发exception,您可以定义一个类来处理本地化错误。

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

然后将其附加到所需的测试用例

 I18n.exception_handler = TestExceptionLocalizationHandler.new 

这样就可以获得exception。 我不知道如何提高失败率(使用flunk)以获得更好的结果。

从Rails 4.1.0开始,现在有一个比4年前这个问题的答案更好的解决方案:在配置文件中添加以下行:

 config.action_view.raise_on_missing_translations = true 

我只想在test环境中设置它,但您可能还想在development设置它。 我强烈建议不要在production中将其设置为真。

我已经创建了这个初始化程序来raiseexception – 传递了args,这样你就会知道哪个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 

资源

Rails 4.1+

要提高i18n翻译缺少exception,您需要件事:

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/environments/test.rb )中的配置设置:

 config.action_view.raise_on_missing_translations = true 

注意:除了exception处理程序之外还需要配置设置,因为rails在其视图中包含对I18n.translate调用,并且帮助程序阻止exception触发。

或者您可以将这些行添加到config/test.rb

  config.action_view.raise_on_missing_translations = true config.i18n.exception_handler = Proc.new { |exception| raise exception.to_exception }