describe Skala::I18n do let(:class_with_i18n_included) do Class.new.tap do |_klass| _klass.send(:include, described_class) end end context "when included into a class" do it "defines a class method #load_locales_from_directory" do expect(class_with_i18n_included).to respond_to(:load_locales_from_directory) end it "defines a class method #locales" do expect(class_with_i18n_included).to respond_to(:locales) end it "defines a class method #translate" do expect(class_with_i18n_included).to respond_to(:translate) end it "defines an instance method .translate" do expect(class_with_i18n_included.new).to respond_to(:translate) end end describe "#load_locales_from_directory" do it "loads all yaml encoded locales from a directory" do loaded_locales = class_with_i18n_included.load_locales_from_directory( File.expand_path("#{File.dirname(__FILE__)}/../assets/locales") ) expect(loaded_locales).not_to be_empty end end describe "#translate" do context "if the class defines .locales" do let(:class_with_i18n_included_and_locales) do Class.new(class_with_i18n_included).tap do |_klass| def _klass.locales load_locales_from_directory( File.expand_path("#{File.dirname(__FILE__)}/../assets/locales") ) end end end let(:object) do class_with_i18n_included_and_locales.new end it "translates the given key into the language specified by the locale option" do translated_key_de = object.translate("field_names.creator", locale: :de) translated_key_en = object.translate("field_names.creator", locale: :en) expected_translation_de = object.class.locales["de"]["field_names"]["creator"] expected_translation_en = object.class.locales["en"]["field_names"]["creator"] expect(translated_key_de).to eq(expected_translation_de) expect(translated_key_en).to eq(expected_translation_en) end it "supports rails style interpolation" do expected_date = "1. Januar 2015" translated_key = object.translate("records.items.loan_status.expected", locale: :de, expected_date: expected_date) expected_translation = object.class.locales["de"]["records"]["items"]["loan_status"]["expected"].gsub("%{expected_date}", expected_date) expect(translated_key).to eq(expected_translation) end context "when there is no translation" do it "returns the last key path" do expect(object.translate("foo.bar.muff", locale: :en)).to eq("muff") end end context "when no locale option is given" do it "raises an exception" do expect { object.translate("field_names.creator") }.to raise_error end end end context "if the class does not define .locales" do let(:object) do class_with_i18n_included.new end it "returns the last key path" do expect(object.translate("foo.bar.muff", locale: :en)).to eq("muff") end end end end