使用I18n惰性查找在rspec中测试助手

Jua*_*tas 4 rspec ruby-on-rails internationalization rails-i18n

考虑这个例子.我有一个产品型号discount_percentage.我们正在维护多个语言环境.在视图中我们不希望i18n的东西搞砸了视图.因此,我们帮助您更好地阅读并可能在其他视图中重复使用它:( render_product_discount代码请参见下文),它将呈现此产品的折扣状态.我们在整个应用程序中使用i18n延迟查找功能.但是当我们想测试这个帮助器方法时,我们得到一个错误:

# RuntimeError:
# Cannot use t(".product_discount") shortcut because path is not available
Run Code Online (Sandbox Code Playgroud)

因为没有path可用于翻译助手来扩展延迟翻译密钥.

预期产量:此产品有20%的折扣.

助手名称: render_product_discount

def render_product_discount
  t('.product_discount', discount_percentage: product.discount_percentage)
end

# es.yml
es:
  products:
    show:
      product_discount: Este producto tiene un %{discount_percentage} descuento.

# en.yml
en:
  products:
    show:
      product_discount: This product has %{discount_percentage} discount.
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?提前致谢.

Seb*_*eer 12

有时您可以设置所需的虚拟路径,以便translate知道如何使用快捷方式.

在助手规范中

before { helper.instance_variable_set(:@virtual_path, "admin.path.form") }
Run Code Online (Sandbox Code Playgroud)

现在t('.word')寻找admin.path.form.word.