【问题标题】:How to test Ruby code with I18n translations in RSpec如何在 RSpec 中使用 I18n 翻译测试 Ruby 代码
【发布时间】:2015-07-21 16:03:19
【问题描述】:

在 RSpec 中使用 I18n 翻译测试 Ruby 代码时,我收到如下错误:

translation missing: en.lib.filter.equal_to

这是一个简化的例子:

def word_for_operator
  I18n.t('lib.filter.equal_to')
end

规格:

it "returns the correct label" do
  expect(filter.word_for_operator).to eq("some value")
end

在 Rails 中一切正常。

如何在我的规范中使用 I18n?

【问题讨论】:

  • 不确定我是否理解您的问题。你是说你有一个有效的 :en 语言环境,但 RSpec 没有使用它?
  • @Stefan 是的,这是正确的。它在将 rails 应用程序用作 gem 或独立运行时有效,但不在规范中。
  • 如果你从它运行测试,你必须将你的 locale.yml 克隆到你的 rails-engine。

标签: ruby-on-rails ruby rspec internationalization rails-i18n


【解决方案1】:

以下内容不能解决您的丑陋问题吗?我了解,这不是您要寻找的解决方案,但已经足够了。

it "returns the correct humanised label" do
    {
      'lib.quattro_filter.none' => 'None',
      'lib.quattro_filter.and' => 'and',
      ...
    }.each do |name, value|
      allow(I18n).to receive(:t).with(name).and_return(value)
    end
    # the same with expects
end

【讨论】:

  • 感谢您的回答,这并不能解决我在每次测试中都需要这样做的问题。会有不少。
猜你喜欢
  • 1970-01-01
  • 2012-10-09
  • 2012-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
相关资源
最近更新 更多