如何为功能测试(Rails)设置locale default_url_options

ins*_*mer 12 testing ruby-on-rails internationalization

在我的application_controller中,我有以下设置来包含具有url_for生成的所有路径的语言环境:

  def default_url_options(options={})
    { :locale => I18n.locale }
  end
Run Code Online (Sandbox Code Playgroud)

我的资源路由有一个:path_prefix ="/:locale"

在网站上正常工作.

但是当涉及到我的功能测试时,:locale不会与生成的url一起传递,因此它们都会失败.我可以通过在我的测试中将语言环境添加到url来解决它,如下所示:

  get :new, :locale => 'en'
Run Code Online (Sandbox Code Playgroud)

但我不想手动将语言环境添加到每个功能测试中.

我尝试将default_url_options def添加到test_helper上面,但似乎没有效果.

有什么办法可以更改default_url_options以包含我所有测试的区域设置吗?

谢谢.

Mar*_*rel 7

在Rails 3.1-stable分支中,处理方法现在位于Behavior模块中.所以这里的代码对我有用(与John Duff的答案略有不同):

class ActionController::TestCase

  module Behavior
    def process_with_default_locale(action, parameters = nil, session = nil, flash = nil, http_method = 'GET')
      parameters = { :locale => I18n.default_locale }.merge( parameters || {} )
      process_without_default_locale(action, parameters, session, flash, http_method)
    end 
    alias_method_chain :process, :default_locale
  end 
end
Run Code Online (Sandbox Code Playgroud)

我确保在运行specs/tests之前调用此代码.放在test_helper类中的好地方.


小智 6

对于Rails 5,我test_helper.rb基于action_dispatch/testing/integration.rb找到了这个简单的解决方案

module ActionDispatch::Integration
  class Session
    def default_url_options
      { locale: I18n.locale }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 我只想添加比使用“ApplicationController”中定义的选项更好的方法,以保持一致性:“ApplicationController.new.send(:default_url_options)” (2认同)

Joh*_*uff 2

查看控制器测试用例如何生成 url,似乎没有直接的方法让它使用 defualt_url_options。实际执行 url 创建(在测试中)的主块如下所示(http://github.com/rails/rails/blob/master/actionpack/lib/action_controller/test_case.rb):

private
  def build_request_uri(action, parameters)
    unless @request.env['REQUEST_URI']
      options = @controller.__send__(:rewrite_options, parameters)
      options.update(:only_path => true, :action => action)

      url = ActionController::UrlRewriter.new(@request, parameters)
      @request.request_uri = url.rewrite(options)
    end
  end
Run Code Online (Sandbox Code Playgroud)

它由 process 方法调用,而 process 方法又由 get、post、head 或 put 方法调用。获得您正在寻找的内容的一种方法可能是对 process 方法进行 alias_chain 。

class ActionController::TestCase
  def process_with_default_locale(action, parameters = nil, session = nil, flash = nil, http_method = 'GET')
    parameters = {:locale=>'en'}.merge(parameters||{})
    process_without_default_locale(action, parameters, session, flash, http_method)
  end
  alias_method_chain :process, :default_locale
end
Run Code Online (Sandbox Code Playgroud)

我认为您需要将其放入 TestCase 类之外的测试助手中。让我知道它对你来说如何工作,我还没有真正测试过它,所以我们会看看。