Search code examples
ruby-on-railstestinglocale

Why can't I change the current locale when testing Rails 3?


I have a multilingual application and I am trying to write some tests for one of my controllers. However, it seems that I cannot change the current locale in testing. It works ok in development. Assume that my test is as follows:

test "do something has to be done correctly" do
  I18n.locale = :cn # set current locale to chinese
  assert_equal :cn, I18n.locale
end

This test fails with error:

<:cn> expected but was
<:en>.

:en is the default locale in my configuration.

Has anybody encountered this problem in Rails 3 before? Any solution found?


Solution

  • Your code, inserted precisely as you have it in a functional test case, works perfectly in a new Rails 3.0.9 application.

    That having been said, setting the locale in I18n.locale within a functional test before calling get or something to test a controller is not going to set the locale in your application's context (only the locale in your test's context).

    Usually you need to merge something like { :locale => :cn } into your parameters, to set the locale for your request. This won't affect the actual test you're showing, but maybe you're not showing precisely what is failing.