加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用I18n惰性查找在rspec中测试帮助程序

发布时间:2020-12-17 01:50:37 所属栏目:百科 来源:网络整理
导读:考虑这个例子.我有一个具有discount_percentage的Product模型.我们正在维护多个语言环境.在视图中我们不希望i18n的东西搞砸了视图.因此,我们帮助您更好地阅读并可能在其他视图中重复使用它:render_product_discount(代码请参见下文),它将呈现此产品的折扣状
考虑这个例子.我有一个具有discount_percentage的Product模型.我们正在维护多个语言环境.在视图中我们不希望i18n的东西搞砸了视图.因此,我们帮助您更好地阅读并可能在其他视图中重复使用它:render_product_discount(代码请参见下文),它将呈现此产品的折扣状态.我们在整个应用程序中使用i18n延迟查找功能.但是当我们想测试这个帮助器方法时,我们得到一个错误:

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

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

预期产量:此产品有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.

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

解决方法

如果你坚持:

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

你可以测试:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读