简体   繁体   中英

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

Controller tests should respect the default_url_options set in the ApplicationController anyway.

To use a default locale for system tests, for Rails 6, adding this snippets to the test_helper.rb file is enough, as stated in the question:

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

For Rails 6.0.1 and 6.0.2, one needs to instead add this beast to the application_system_test_case.rb file:

  # See actionpack/lib/action_dispatch/system_test_case.rb
  def initialize(*)
    super
    @proxy_route = if ActionDispatch.test_app
      Class.new do
        include ActionDispatch.test_app.routes.url_helpers
        include ActionDispatch.test_app.routes.mounted_helpers

        def url_options
          default_url_options.merge(host: Capybara.app_host, locale: I18n.locale)
        end
      end.new
    else
      nil
    end
  end

Following this Rails issue you may be able to access default_url_options without a monkey patch:

ActionDispatch::IntegrationTest.app.default_url_options[:locale] = I18n.locale

However I would suggest manually passing the locale param every time.

I had the same issue with an application and ended up manually setting the param in all tests. It's tedious the first time but it ends up making all calls clearer and helps rely less on code specifically for the test suite.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM