Maintainable I18n with Rails and AngularJS

by Alessandro Desantis

angular-translate is one of the coolest AngularJS modules available out there. It’s elegant, flexible, and extensible beyond common sense.

However, when I was building my first application with Angular and Rails, I found that there was no easy way to test the whole thing with RSpec and Capybara, as I didn’t have access to the translations.

I came up with a few ideas, but they weren’t really ideal (pun intended):

  1. I could write my translations in Rails and then somehow copy them into static JS files, maybe with a Rake task, but it didn’t seem too elegant.
  2. I could enforce a specific locale and use literal strings in my tests. Needless to say, this one was pure madness.

It didn’t immediately occur to me that I could somehow serve all the translations via AJAX.


So, I ended up creating a translations_controller.rb:

Then, I configured my application to use angular-translate-loader-static-files (you’ll have to install it separately):

You will also have to add the routes to your config/routes.rb:


Let’s test this! First, we’ll create a HomeController with Angular. To do that, we’ll edit our app.js like this:

And here’s the corresponding home.html view:

Now, we’ll need to put our translation(s) in config/locales/en.yml (or wherever you told Rails to look for them):

If you load your app now, you should see the “Hello, world!” heading.

At this point, writing an integration test with Capybara is quite straightforward. All we have to do is create a spec/features/home_spec.rb file containing something like this:


Note: With a few more lines of code, you could also expand this to have it load only specific domains of your translations instead of everything at once (have a look at angular-translate’s partialLoader if you want to know how).