Skip to content

Instantly share code, notes, and snippets.

@patrick99e99
Last active February 6, 2020 16:25
Show Gist options
  • Save patrick99e99/5256900 to your computer and use it in GitHub Desktop.
Save patrick99e99/5256900 to your computer and use it in GitHub Desktop.
I18n matchers for rspec 2
RSpec::Matchers.define :translate_to do |key, options|
match do |actual|
@expected = I18n.t(key, options)
@failure = nil
@failure ||= :bad_actual if actual.start_with?('translation missing:')
@failure ||= :bad_expected if @expected.start_with?('translation missing:')
@failure ||= :no_match if @expected != actual
@failure.nil?
end
failure_message_for_should do |actual|
if @failure == :no_match
"expected \"#{expected}\" to equal \"#{actual}\" but it does not."
else
"missing translation for I18n.t('#{key}'#{options ? ", #{options}" : ''})."
end
end
end
RSpec::Matchers.define :have_translation_for do |key, options|
match do |actual|
@expected = I18n.t(key, options)
@failure = nil
@failure ||= :bad_expected if @expected.start_with?('translation missing:')
@failure ||= :bad_actual if actual.include?('translation missing:')
@failure ||= :no_match if !actual.include?(@expected)
@failure.nil?
end
failure_message_for_should do |actual|
case @failure
when :no_match
['expected:', actual, "to include \"#{@expected}\" but it does not."].join("\n")
when :bad_actual
['actual:', actual, 'has missing translations.'].join("\n")
when :bad_expected
"missing translation for I18n.t('#{key}'#{options ? ", #{options}" : ''})."
end
end
end
RSpec::Matchers.define :have_missing_translations do
match do |actual|
actual =~ /translation missing:|%{.+}/
end
failure_message_for_should do |actual|
[actual, 'should have missing translations.'].join("\n")
end
failure_message_for_should_not do |actual|
['expected:', actual, 'to not have missing translations.'].join("\n")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment