问题
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
because there is no path
available for translation helper to expand the lazy translation key.
Expected Output: This product has 20% discount.
Helper name: 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.
回答1:
if you stub t as:
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.")
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.
回答2:
Sometimes you can set the needed virtual path, so that translate knows how to use shortcuts.
In Helper Specs
before { helper.instance_variable_set(:@virtual_path, "admin.path.form") }
Now t('.word')
looks for admin.path.form.word
.
来源:https://stackoverflow.com/questions/21774156/testing-helper-in-rspec-with-i18n-lazy-lookup