allow_value.with_message takes i18n interp values

This commit is contained in:
Elliot Winkler 2014-04-26 11:10:17 -04:00
parent d4b1fc2fa1
commit 01c9d08c8e
4 changed files with 45 additions and 4 deletions

View File

@ -1,5 +1,13 @@
# HEAD
## Features
* Teach `with_message` qualifier on `allow_value` to accept a hash of i18n
interpolation values:
`allow_value('foo').for(:attr).with_message(:greater_than, values: { count: 20 })`.
## Bug fixes
* Fix `ComparisonMatcher` so that `validate_numericality_of` comparison matchers
work with large numbers.

View File

@ -53,9 +53,12 @@ module Shoulda # :nodoc:
def with_message(message, options={})
self.options[:expected_message] = message
self.options[:expected_message_values] = options.fetch(:values, {})
if options.key?(:against)
self.attribute_to_check_message_against = options[:against]
end
self
end
@ -173,10 +176,18 @@ module Shoulda # :nodoc:
def default_attribute_message
default_error_message(
options[:expected_message],
default_attribute_message_values
)
end
def default_attribute_message_values
defaults = {
model_name: model_name,
instance: instance,
attribute: attribute_to_set
)
attribute: attribute_to_set,
}
defaults.merge(options[:expected_message_values])
end
def model_name

View File

@ -68,6 +68,24 @@ describe Shoulda::Matchers::ActiveModel::AllowValueMatcher do
expect(validating_format(with: /abc/, message: 'bad value')).
not_to allow_value('xyz').for(:attr).with_message(/bad/)
end
it 'allows interpolation values for the message to be provided' do
options = {
attribute_name: :attr,
attribute_type: :string
}
record = record_with_custom_validation(options) do
if self.attr == 'xyz'
self.errors.add :attr, :greater_than, count: 2
end
end
expect(record).
not_to allow_value('xyz').
for(:attr).
with_message(:greater_than, values: { count: 2 })
end
end
context 'an attribute where the message occurs on another attribute' do

View File

@ -1,11 +1,15 @@
module ActiveModelHelpers
def custom_validation(&block)
define_model(:example, attr: :integer) do
def custom_validation(options = {}, &block)
attribute_name = options.fetch(:attribute_name, :attr)
attribute_type = options.fetch(:attribute_type, :integer)
define_model(:example, attribute_name => attribute_type) do
validate :custom_validation
define_method(:custom_validation, &block)
end.new
end
alias record_with_custom_validation custom_validation
def validating_format(options)
define_model :example, attr: :string do