From 3e8845131ec7822951c3ec276099a3465e4fb249 Mon Sep 17 00:00:00 2001 From: EduardoSCosta Date: Wed, 8 Mar 2023 15:19:13 -0300 Subject: [PATCH] create against method in allow value matcher --- .../active_model/allow_value_matcher.rb | 36 +++++++++++++++++++ .../active_model/allow_value_matcher_spec.rb | 12 +++++++ 2 files changed, 48 insertions(+) diff --git a/lib/shoulda/matchers/active_model/allow_value_matcher.rb b/lib/shoulda/matchers/active_model/allow_value_matcher.rb index 660514fa5..29d2aa3a0 100644 --- a/lib/shoulda/matchers/active_model/allow_value_matcher.rb +++ b/lib/shoulda/matchers/active_model/allow_value_matcher.rb @@ -169,6 +169,36 @@ module ActiveModel # on(:create) # end # + # ##### against + # + # Use `against` if the validation is on an attribute + # other than the attribute being validated: + # + # class UserProfile + # include ActiveModel::Model + # attr_accessor :website_url + # + # alias_attribute :url, :website_url + # + # validates_format_of :url, with: URI.regexp + # end + # + # # RSpec + # RSpec.describe UserProfile, type: :model do + # it do + # should allow_value('https://foo.com'). + # for(:website_url). + # against(:url) + # end + # end + # + # # Minitest (Shoulda) + # class UserProfileTest < ActiveSupport::TestCase + # should allow_value('https://foo.com'). + # for(:website_url). + # against(:url) + # end + # # ##### with_message # # Use `with_message` if you are using a custom validation message. @@ -349,6 +379,12 @@ def on(context) self end + def against(attribute) + @attribute_to_check_message_against = attribute if attribute.present? + + self + end + def with_message(message, given_options = {}) if message.present? @expects_custom_validation_message = true diff --git a/spec/unit/shoulda/matchers/active_model/allow_value_matcher_spec.rb b/spec/unit/shoulda/matchers/active_model/allow_value_matcher_spec.rb index d7c6556fb..8e9243976 100644 --- a/spec/unit/shoulda/matchers/active_model/allow_value_matcher_spec.rb +++ b/spec/unit/shoulda/matchers/active_model/allow_value_matcher_spec.rb @@ -366,6 +366,18 @@ end end + context 'when the attribute that receives the validation error is provided' do + context 'given a valid value' do + it 'accepts' do + builder = builder_for_record_with_different_error_attribute + expect(builder.record). + to allow_value(builder.valid_value). + for(builder.attribute_to_validate). + against(builder.attribute_that_receives_error) + end + end + end + context 'when the validation error message was provided directly' do context 'given a valid value' do it 'accepts' do