ruby-on-railsruby-on-rails-6

Set locale via default_url_options for Rails tests (Rails 6 and newer)


Is there a reliable way to set the locale via default_url_options for Rails tests (controller and system tests) globally, without having to pass the locale manually to url helpers?

Prior to Rails 6.0.1, this used to work:

# Set locale via default_url_options
class ActionDispatch::Routing::RouteSet
  def default_url_options(options = {})
    { locale: I18n.locale }.merge options
  end
end

Solution

  • It's still tricky to get this right in Rails 7, but fortunately much more straightforward compared to Rails 6.

    It can be done by adding this line in config/environments/test.rb:

    Rails.application.routes.default_url_options[:locale] = I18n.default_locale
    

    Or by adding this in test_helper.rb:

    class ActiveSupport::TestCase
      setup do
        Rails.application.routes.default_url_options[:locale] = I18n.default_locale
      end
    

    However, neither of the above solutions solve the issue for system tests. To address that, add this into application_system_test_case.rb:

    class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
      ...
    
      setup do
        default_url_options[:locale] = I18n.default_locale
      end