Search code examples
ruby-on-railstestinginternationalization

How to set locale default_url_options for functional tests (Rails)


In my application_controller, I have the following set to include the locale with all paths generated by url_for:

  def default_url_options(options={})
    { :locale => I18n.locale }
  end

My resource routes then have a :path_prefix = "/:locale"

Works fine on the site.

But when it comes to my functional tests, the :locale is not passed with the generated urls, and therefore they all fail. I can get around it by adding the locale to the url in my tests, like so:

  get :new, :locale => 'en'

But I don't want to have to manually add the locale to every functional test.

I tried adding the default_url_options def above to test_helper, but it seems to have no effect.

Is there any way I can change the default_url_options to include the locale for all my tests?

Thanks.


Solution

  • Looking through how the controller test case generates the url there doesn't seem to be a direct way to have it use the defualt_url_options. The main block that actually does the url creationg (in the tests) looks like this (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
    

    This gets called by the process method which is in turn called by the get, post, head, or put methods. One way to maybe get what you are looking for might be to alias_chain the process method.

    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
    

    You'll want to put that into your test helper, outside of the TestCase class I think. Let me know how it works for you, I haven't really tested it out so we'll see.