如何在集成测试的默认URL选项中设置区域设置

时间:2013-03-15 17:10:44

标签: ruby-on-rails integration-testing ruby-on-rails-4

使用Rails 4.0.0beta1,我正在尝试创建一些集成测试。 我的所有网址都是locale(例如/en/user/new),我每次尝试拨打new_user_url时都会出现以下错误:

ActionController::UrlGenerationError: No route matches {:action=>"new", :controller=>"user"} missing required keys: [:locale]

我在following question

尝试了@Balint Erdi提供的解决方案
class ActionController::Integration::Session
  def url_for_with_default_locale(options)
    options = { locale: I18n.locale }.merge(options)
    url_for_without_default_locale(options)
  end

  alias_method_chain :url_for, :default_locale
end

它有效,但由于rails4:

而给我一个弃用警告
DEPRECATION WARNING: ActionController::Integration is deprecated and will be removed, use ActionDispatch::Integration instead. (called from <top (required)> at /path/to/project/test/test_helper.rb:46)
DEPRECATION WARNING: ActionController::IntegrationTest is deprecated and will be removed, use ActionDispatch::IntegrationTest instead. (called from <top (required)> at /path/to/project/test/test_helper.rb:46)

对于我的控制器测试,我添加了这个:

class ActionController::TestCase

  module Behavior
    def process_with_default_locale(action, http_method = 'GET', parameters = nil, session = nil, flash = nil)
      parameters = { locale: I18n.locale }.merge( parameters || {} ) 
      process_without_default_locale(action, http_method, parameters, session, flash)
    end

    alias_method_chain :process, :default_locale
  end 
end

我还测试了将default_url_options方法直接添加到测试中,但它没有用。

如何在集成测试中设置默认的url参数?

3 个答案:

答案 0 :(得分:3)

对我有用的选项(至少在Rails 4.2.0中)是在ActionDispatch::IntegrationTest中为test/test_helper.rb类添加设置方法:

class ActionDispatch::IntegrationTest
  def setup
    self.default_url_options = { locale: I18n.default_locale }
  end
end

答案 1 :(得分:1)

好吧,看起来就像用ActionController替换ActionDispatch一样简单。我不知道为什么它之前没有用,但是因为我更新到最新的rails rake test:integration rails test integration它似乎有效:

class ActionDispatch::Integration::Session
  def url_for_with_default_locale(options)
    options = { locale: I18n.locale }.merge(options)
    url_for_without_default_locale(options)
  end

  alias_method_chain :url_for, :default_locale
end

答案 2 :(得分:0)

Rails 5,Minitest示例:

class SomeTest < ActionDispatch::IntegrationTest
  setup do
    self.default_url_options = { locale: I18n.default_locale }
  end

  def test_something
    ...
  end
end