Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
insane.dreamer Avatar asked Dec 31 '09 22:12

insane.dreamer


2 Answers

For Rails 5, I found this simple solution In test_helper.rb based on action_dispatch/testing/integration.rb

module ActionDispatch::Integration
  class Session
    def default_url_options
      { locale: I18n.locale }
    end
  end
end
like image 81
Webak Avatar answered Oct 05 '22 18:10

Webak


In the Rails 3.1-stable branch, the process method is now within a Behavior module. So here is the code which worked for me (slightly different from John Duff's answer):

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

And I made sure this code gets called before running the specs/tests. A good place to put it is in the test_helper class.

like image 42
Martin Carel Avatar answered Oct 05 '22 17:10

Martin Carel