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):

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. 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.

Configuration

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:

Usage

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:

Done!