是否有一种可靠的方法可以通过 default_url_options
全局设置 Rails 测试( Controller 和系统测试)的语言环境,而无需手动将语言环境传递给 url 帮助程序?
在 Rails 6.0.1 之前,这曾经有效:
# Set locale via default_url_options
class ActionDispatch::Routing::RouteSet
def default_url_options(options = {})
{ locale: I18n.locale }.merge options
end
end
最佳答案
无论如何, Controller 测试都应该尊重 ApplicationController
中设置的 default_url_options
。
要使用系统测试的默认区域设置,对于 Rails 6,将此代码段添加到 test_helper.rb
文件就足够了,如问题中所述:
class ActionDispatch::Routing::RouteSet
def default_url_options(options = {})
{ locale: I18n.locale }.merge options
end
end
对于 Rails 6.0.1 和 6.0.2,需要将这个野兽添加到 application_system_test_case.rb
文件中:
# 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
关于ruby-on-rails - 通过 default_url_options 设置区域设置以进行 Rails 测试(Rails 6 及更高版本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59295991/