【问题标题】:How to set locale in default url options for integration tests如何在集成测试的默认 url 选项中设置语言环境
【发布时间】:2013-03-15 17:10:43
【问题描述】:

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

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

我已经尝试了@Balint Erdi 在following question 中给出的解决方案

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 参数?

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      好的,看起来就像用ActionDispatch 替换ActionController 一样简单。我不知道为什么它以前不起作用,但自从我更新到最新的 rails 后,它弃用了 rake test:integration for 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
      

      【讨论】:

        【解决方案3】:

        Rails 5,Minitest 示例:

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

        【讨论】:

          猜你喜欢
          • 2016-09-07
          • 2014-09-14
          • 2012-02-07
          • 1970-01-01
          • 2020-04-05
          • 1970-01-01
          • 1970-01-01
          • 2015-02-04
          • 1970-01-01
          相关资源
          最近更新 更多