3

I'm working on a feature in a Rails app that depends on a locale-specific piece of information. In testing, I want to show that some behavior depends on what the locale contains.

How can I dynamically add or edit translations to be used by I18n.t in testing?

Nathan Long
  • 122,748
  • 97
  • 336
  • 451

1 Answers1

4

I18n.backend.store_translations

# Will add a key or overwrite the existing value
I18n.backend.store_translations("en", {cat: "cat"})
I18n.backend.store_translations("es", {cat: "gato"})

I18n.t(:cat, locale: "en") # => "cat"
I18n.t(:cat, locale: "es") # => "gato"

Note that you cannot add keys for arbitrary locales this way; you'll get I18n::InvalidLocale. To determine available locales, you can use:

existing_locales = I18n.config.available_locales
new_locales      = existing_locales + Set.new(["es", :es])
I18n.config.available_locales = new_locales

Finally, note that if you make a global change like that for testing, you'll probably want to change it back to cleanup after your test so that other tests aren't affected.

Nathan Long
  • 122,748
  • 97
  • 336
  • 451