Skip to content

Commit

Permalink
create against method in allow value matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
EduardoSCosta committed Mar 8, 2023
1 parent 195153c commit 4c2d8ef
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
36 changes: 36 additions & 0 deletions lib/shoulda/matchers/active_model/allow_value_matcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 4c2d8ef

Please sign in to comment.