From f932fcd12529525d006d33d3a8ae0b2d3a1b97b8 Mon Sep 17 00:00:00 2001 From: Juarez Lustosa Date: Fri, 24 Jul 2020 12:50:57 -0300 Subject: [PATCH] Add interpolation value on the messages --- .../matchers/active_model/validator.rb | 8 +++++++- .../validate_inclusion_of_matcher_spec.rb | 19 ++++++++++++++----- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/lib/shoulda/matchers/active_model/validator.rb b/lib/shoulda/matchers/active_model/validator.rb index 426437296..520aec690 100644 --- a/lib/shoulda/matchers/active_model/validator.rb +++ b/lib/shoulda/matchers/active_model/validator.rb @@ -67,12 +67,18 @@ def messages def matched_messages if @expected_message - messages.grep(@expected_message) + messages.grep(interpolate_expected_message) else messages end end + def interpolate_expected_message + return @expected_message unless @expected_message.is_a?(String) + + @expected_message.gsub(/%{value}/, record.send(attribute).to_s) + end + def captured_range_error? !!@captured_range_error end diff --git a/spec/unit/shoulda/matchers/active_model/validate_inclusion_of_matcher_spec.rb b/spec/unit/shoulda/matchers/active_model/validate_inclusion_of_matcher_spec.rb index bc18c2d50..09091ef25 100644 --- a/spec/unit/shoulda/matchers/active_model/validate_inclusion_of_matcher_spec.rb +++ b/spec/unit/shoulda/matchers/active_model/validate_inclusion_of_matcher_spec.rb @@ -16,6 +16,7 @@ it 'matches ensuring the correct range and messages' do expect_to_match_ensuring_range_and_messages(2..5, 2, 5) expect_to_match_ensuring_range_and_messages(2...5, 2, 4) + expect_to_match_ensuring_range_and_messages(2..5, 2, 5, "%{value}") end end @@ -1083,17 +1084,17 @@ def expect_not_to_match_in_range(builder, range) end end - def expect_to_match_ensuring_range_and_messages(range, low_value, high_value) - low_message = 'too low' - high_message = 'too high' + def expect_to_match_ensuring_range_and_messages(range, low_value, high_value, with_value=nil) + low_message = menssage_constructor('low', "#{with_value}") + high_message = menssage_constructor('high', "#{with_value}") builder = build_object custom_validation: -> (object, attribute) { value = object.public_send(attribute) if value < low_value - object.errors.add(attribute, low_message) + object.errors.add(attribute, add_value_to_message(low_message, value)) elsif value > high_value - object.errors.add(attribute, high_message) + object.errors.add(attribute, add_value_to_message(high_message, value)) end } @@ -1105,6 +1106,14 @@ def expect_to_match_ensuring_range_and_messages(range, low_value, high_value) end end + def add_value_to_message(message, value) + message.gsub(/%{value}/, value.to_s) + end + + def menssage_constructor(string, value) + "#{value} too #{string}" + end + def validation_matcher_scenario_args super.deep_merge(matcher_name: :validate_inclusion_of) end