本文介绍了使用I18n惰性查找在RSpec中测试助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例.我有一个具有discount_percentage的产品模型.而且我们正在维护多个语言环境.在视图中,我们不希望i18n的东西弄乱了视图.因此,我们将帮助您更好地阅读并可能在其他视图中重复使用它:render_product_discount(代码请参见下文),它将显示此产品的折扣状态.而且,我们在整个应用程序中都使用了i18n惰性查找功能.但是,当我们要测试此辅助方法时,会出现错误:

Consider this example. I have a Product model which has discount_percentage. And we're maintaining multiple locales. In the view we do not want the i18n stuff mess up the view. So we make a helper to read better and probably reuse it in other views: render_product_discount (code please see below) which will render the discount status of this product. And we use i18n lazy lookup feature throughout the application. But when we want to test this helper method we get a Error:

# RuntimeError:
# Cannot use t(".product_discount") shortcut because path is not available

因为没有path可用于翻译助手来扩展惰性翻译键.

because there is no path available for translation helper to expand the lazy translation key.

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

Expected Output: This product has 20% discount.

助手名称: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.

如何解决此问题?预先感谢.

How to workaround this? Thanks in advance.

推荐答案

,如果您存根为:

helper.stub(:t).with('.product_discount', discount_percentage: product.discount_percentage) { "This product has #{product.discount_percentage}% discount." }

您可以使用以下方法进行测试:

you can test with:

expect(helper.render_product_discount).to eq("This product has #{product.discount_percentage}% discount.")

修改
正如SebastianG回答的那样,您可以将@virtual_path设置为预期的使用路径,就像在主代码中一样,我认为这是一种更好的方法.

Edit
As SebastianG answered, you can set @virtual_path with the expected path to use like in the main code, what I think it´s a better approach when possible.

这篇关于使用I18n惰性查找在RSpec中测试助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:13