Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing helper in rspec with I18n lazy lookup

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.

like image 998
Juanito Fatas Avatar asked Dec 08 '22 09:12

Juanito Fatas


2 Answers

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.

like image 105
Sebastian vom Meer Avatar answered Dec 20 '22 16:12

Sebastian vom Meer


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.

like image 33
Doguita Avatar answered Dec 20 '22 16:12

Doguita