Skip to content

Commit

Permalink
Add tests and error handling for non-string translations
Browse files Browse the repository at this point in the history
  • Loading branch information
tom-lord committed Mar 23, 2024
1 parent d55f40a commit afb20cb
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/i18n.rb
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,10 @@ def interpolation_keys(key, **options)

return [] unless exists?(key, **options.slice(:locale, :scope))

translate(key, **options.slice(:locale, :scope))
translation = translate(key, **options.slice(:locale, :scope))

raise I18n::NonStringTranslationError unless translation.is_a?(String)
translation
.scan(Regexp.union(I18n.config.interpolation_patterns))
.flatten
.compact
Expand Down
2 changes: 2 additions & 0 deletions lib/i18n/exceptions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,6 @@ def initialize(file_errors)
MSG
end
end

class NonStringTranslationError < ArgumentError; end
end
23 changes: 23 additions & 0 deletions test/i18n_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,29 @@ def setup
assert_equal I18n.config.available_locales.size * 2, I18n.config.available_locales_set.size
end

test "interpolation_keys returns an array of keys" do
store_translations(:en, "example_two" => "Two interpolations %{foo} %{bar}")
assert_equal ["foo", "bar"], I18n.interpolation_keys("example_two")
end

test "interpolation_keys returns an empty array when no interpolations " do
store_translations(:en, "example_zero" => "Zero interpolations")
assert_equal [], I18n.interpolation_keys("example_zero")
end

test "interpolation_keys returns an empty array when missing translation " do
assert_equal [], I18n.interpolation_keys("does-not-exist")
end

test "interpolation_keys raises I18n::ArgumentError when non-string argument" do
assert_raises(I18n::ArgumentError) { I18n.interpolation_keys(["bad-argument"]) }
end

test "interpolation_keys raises I18n::NonStringTranslationError when translation is not a String" do
store_translations(:en, "example_nested" => { "one" => "One", "two" => "Two" })
assert_raises(I18n::NonStringTranslationError) { I18n.interpolation_keys("example_nested") }
end

test "exists? given an existing key will return true" do
assert_equal true, I18n.exists?(:currency)
end
Expand Down

0 comments on commit afb20cb

Please sign in to comment.