Skip to content

Instantly share code, notes, and snippets.

@stex
Created April 28, 2014 16:28
Show Gist options
  • Save stex/11377025 to your computer and use it in GitHub Desktop.
Save stex/11377025 to your computer and use it in GitHub Desktop.
Unit-Testing for specific localized error messages
#test/test_helper.rb
#
# Looks up the error message for the given error in the locales
#
def localized_validation_error_message(record, attribute, error_name)
I18n.t("activerecord.errors.models.#{record.class.name.underscore}.attributes.#{attribute}.#{error_name}")
end
#
# @return [Boolean] +true+ if the given error was actually included in the validation errors
#
# @example Check if a certain localized error was included
# localized_validation_error?(my_domain, :name, :invalid_subdomain_format)
#
def localized_validation_error?(record, attribute, error_name)
Array(record.errors.get(attribute)).include?(localized_validation_error_message(record, attribute, error_name))
end
# Example:
# my_model.rb:
# validates_presence_of :some_attribute, :message => :some_error
#
# test/models/my_model_test.rb:
# should 'Add a cool error to the instance' do
# my_model = MyModel.create(some_data)
# => false
# assert localized_validation_error? my_model, :some_attribute, :some_error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment