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 context "when the including class has a class variable named @@locales" do let(:value_of_locales) do { foo: "bar" } end let(:klass) do Class.new.tap do |_klass| _klass.class_variable_set(:@@locales, value_of_locales) _klass.send(:include, described_class) end end it "does not alter the existing class variable" do expect(klass.class_variable_get(:@@locales)).to eq(value_of_locales) end end context "when the including class has no class variable named @@locales" do let(:klass) do Class.new.tap do |_klass| _klass.send(:include, described_class) end end it "defines a class variable named @@locales as an empty hash" do expect(klass.class_variable_get(:@@locales)).to eq({}) end end 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 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 and adds them to @@locales" do class_with_i18n_included.load_locales_from_directory(File.expand_path("#{File.dirname(__FILE__)}/../assets/locales")) expect(class_with_i18n_included.class_variable_get(:@@locales)).not_to be_empty end end describe "#translate" do let(:object) do class_with_i18n_included.new.tap do |_object| _object.class.load_locales_from_directory(File.expand_path("#{File.dirname(__FILE__)}/../assets/locales")) end 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.class_variable_get(:@@locales)["de"]["field_names"]["creator"] expected_translation_en = object.class.class_variable_get(:@@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.class_variable_get(:@@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 to 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 end