osgdba
Last Updated: February 25, 2016
·
3.04K
· notgary
Ba6aba5790e7412dd4f6041c42a24c7e

Using I18n translations in fast Rails specs

rspec-rails provides spec_helper.rb for loading your Rails app into your RSpec environment, which is nice and convenient, but when your project reaches a certain size, you want to stop using that and only load the bits you need. In doing so, you loose access to the library of translations you would get through I18n, but there is an easy way to populate the translation store during your test.

require 'i18n'

def baz_translated
  I18n.t('foo.bar.baz')
end

describe 'using translations in tests' do
  before do
    I18n.backend.store_translations(:en, {
      foo: {
        bar: {
          baz: 'Baz'
        }
      }
    })
  end

  it 'translates text in the spec' do
    expect(baz_translated).to eq('Baz')
  end
end

If you do need access to the existing translations, then you can still get them without loading the whole of Rails by doing

require 'yaml'
require 'i18n'

 I18n.backend.store_translations(:en,
  YAML.load_file(File.open('./config/locales/en.yml'))['en']
)

You can store as many languages as your test requires by using I18n.backend.store_translations with whatever locale key (:sv, :no, etc)

Say Thanks
Respond