Modify Rails i18n config during a test?

624 Views Asked by At

I'm trying to test a Rails plugin to make sure that the correct action is performed with or without fallbacks turned on. Inside my Dummy application's configuration, I have:

module Dummy
  class Application < Rails::Application
    config.i18n.fallbacks = true
  end
end

How can I flip this back to false for a specific test? So far I have tried:

Dummy::Application.config.i18n.fallbacks = false
Dummy::Application.configure do |app|
  app.config.i18n.fallbacks = false
end
Rails.application.config.i18n.fallbacks = false

All to no avail.

1

There are 1 best solutions below

1
Larry Lv On

This is an interesting question, actually once the app got initialized in the beginning, you couldn't change i18n configuration because it already got memoized with these codes:

# Setup i18n configuration.
def self.initialize_i18n(app)
  return if @i18n_inited
  ...
  @i18n_inited = true
end

And I18n.fallbacks was set with this line

I18n.fallbacks = I18n::Locale::Fallbacks.new(*args)

When you specify the callbacks as true, I18n.fallbacks has a value of

[1] pry(main)> I18n.fallbacks
=> {}
[2] pry(main)> I18n.fallbacks.class
=> I18n::Locale::Fallbacks

And I18n.fallbacks is used in this way:

locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks

As long as I18n.respond_to? :fallbacks, the app will always have fallbacks feature turned on.

The method is defined here in I18n:

def fallbacks
  @@fallbacks ||= I18n::Locale::Fallbacks.new
end

To turn off the fallbacks feature, the only way is to make I18n.respond_to? :fallbacks return false.

Here you go:

class << I18n
  remove_method :fallbacks
end