diff --git a/lib/shoulda/matchers/active_model/allow_value_matcher.rb b/lib/shoulda/matchers/active_model/allow_value_matcher.rb index 023e0833b..504dce68c 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 881758a1f..8fb9d2ccb 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 @@ -354,6 +354,18 @@ context 'when the attribute being validated is different than the attribute that receives the validation error' do include UnitTests::AllowValueMatcherHelpers + 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