Last Updated: February 25, 2016
·
1.583K
· dinks

Mock I18n for Rspec

We had been having a lot of problems with the I18n mocks for rspec. Normally we should only test if a key exists and not the actual value translated as this can change with respect to the user language. And seeming, it seems that the mock of I18n is not that easy.

Instead of doing aliases for the translate method of I18n, we created our own class inherited from the I18n::Backend::Simple and mocked the returns.

module I18n
  module Backend
    class SimpleMock < Simple
      def translate(locale, key, options = {})
        key_with_interpolations = key.to_s + "#{options.map(&:to_s).join(",")}"

        case super(:en_dev, key, options)
        when String
          key_with_interpolations
        when Array
          [key_with_interpolations]
        when Hash
          {}
        end
      end
    end
  end
end

I18n.backend = I18n::Backend::SimpleMock.new