简体   繁体   中英

How to set locale in default url options for integration tests

Using Rails 4.0.0beta1, i'm trying to create some integration tests. All my URLs are scoped with me locale (eg /en/user/new ) and i'm having the following error each time i try to call new_user_url :

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

I've tried the solution given by @Balint Erdi in the 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

It works but gives me a deprecation warning because of 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)

For my controller tests i added this :

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

I've also tested adding a default_url_options method directly into the tests but it did not work.

How can i set the default url parameters in integration tests ?

An option that worked for me (at least in Rails 4.2.0) was to add a setup method to the ActionDispatch::IntegrationTest class in my test/test_helper.rb :

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

Ok, it seems it's as easy as replacing ActionController by ActionDispatch . I don't know why it didn't work before but since I updated to the latest rails which deprecates rake test:integration for rails test integration it seems to work:

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

Rails 5, Minitest example:

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

  def test_something
    ...
  end
end

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