Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clear up confusion w/ presence around belongs_to associations #1214

Merged
merged 2 commits into from
Jun 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 86 additions & 11 deletions lib/shoulda/matchers/active_model/validate_presence_of_matcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,27 @@ def simple_description
"validate that :#{@attribute} cannot be empty/falsy"
end

def failure_message
message = super

if should_add_footnote_about_belongs_to?
message << "\n\n"
message << Shoulda::Matchers.word_wrap(<<-MESSAGE.strip, indent: 2)
You're getting this error because #{reason_for_existing_presence_validation}.
*This* presence validation doesn't use "can't be blank", the usual validation
message, but "must exist" instead.

With that said, did you know that the `belong_to` matcher can test this
validation for you? Instead of using `validate_presence_of`, try the following
instead:

it { should #{representation_of_belongs_to} }
MESSAGE
end

message
end

private

def secure_password_being_validated?
Expand All @@ -197,7 +218,7 @@ def possibly_ignore_interference_by_writer
def allows_and_double_checks_value_of!(value)
allows_value_of(value, @expected_message)
rescue ActiveModel::AllowValueMatcher::AttributeChangedValueError
raise ActiveModel::CouldNotSetPasswordError.create(@subject.class)
raise ActiveModel::CouldNotSetPasswordError.create(model)
end

def allows_original_or_typecast_value?(value)
Expand All @@ -207,7 +228,7 @@ def allows_original_or_typecast_value?(value)
def disallows_and_double_checks_value_of!(value)
disallows_value_of(value, @expected_message)
rescue ActiveModel::AllowValueMatcher::AttributeChangedValueError
raise ActiveModel::CouldNotSetPasswordError.create(@subject.class)
raise ActiveModel::CouldNotSetPasswordError.create(model)
end

def disallows_original_or_typecast_value?(value)
Expand All @@ -218,25 +239,79 @@ def disallowed_values
if collection?
[Array.new]
else
[''].tap do |disallowed|
if !expects_to_allow_nil?
disallowed << nil
end
values = []

if !association_being_validated?
values << ''
end

if !expects_to_allow_nil?
values << nil
end

values
end
end

def collection?
if reflection
[:has_many, :has_and_belongs_to_many].include?(reflection.macro)
if association_reflection
[:has_many, :has_and_belongs_to_many].include?(
association_reflection.macro,
)
else
false
end
end

def reflection
@subject.class.respond_to?(:reflect_on_association) &&
@subject.class.reflect_on_association(@attribute)
def should_add_footnote_about_belongs_to?
belongs_to_association_being_validated? &&
presence_validation_exists_on_attribute?
end

def reason_for_existing_presence_validation
if belongs_to_association_configured_to_be_required?
"you've instructed your `belongs_to` association to add a " +
'presence validation to the attribute'
else
# assume ::ActiveRecord::Base.belongs_to_required_by_default == true
'ActiveRecord is configured to add a presence validation to all ' +
'`belongs_to` associations, and this includes yours'
end
end

def representation_of_belongs_to
'belong_to(:parent)'.tap do |str|
if association_reflection.options.include?(:optional)
str << ".optional(#{association_reflection.options[:optional]})"
end
end
end

def belongs_to_association_configured_to_be_required?
association_reflection.options[:optional] == false ||
association_reflection.options[:required] == true
end

def belongs_to_association_being_validated?
association_being_validated? &&
association_reflection.macro == :belongs_to
end

def association_being_validated?
!!association_reflection
end

def association_reflection
model.respond_to?(:reflect_on_association) &&
model.reflect_on_association(@attribute)
end

def presence_validation_exists_on_attribute?
model._validators.include?(@attribute)
end

def model
@subject.class
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/shoulda/matchers/active_record/association_matcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ module ActiveRecord
# should belong_to(:organization).required
# end
#
# #### without_validating_presence
# ##### without_validating_presence
#
# Use `without_validating_presence` with `belong_to` to prevent the
# matcher from checking whether the association disallows nil (Rails 5+
Expand Down
7 changes: 4 additions & 3 deletions lib/shoulda/matchers/util/word_wrap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ module Shoulda
module Matchers
# @private
module WordWrap
TERMINAL_WIDTH = 72

def word_wrap(document, options = {})
Document.new(document, options).wrap
end
Expand Down Expand Up @@ -112,7 +114,6 @@ def combine_paragraph_into_one_line

# @private
class Line
TERMINAL_WIDTH = 72
OFFSETS = { left: -1, right: +1 }

def initialize(line, indent: 0)
Expand Down Expand Up @@ -171,7 +172,7 @@ def read_indentation
def wrap_line(line, direction: :left)
index = nil

if line.length > TERMINAL_WIDTH
if line.length > Shoulda::Matchers::WordWrap::TERMINAL_WIDTH
index = determine_where_to_break_line(line, direction: :left)

if index == -1
Expand All @@ -192,7 +193,7 @@ def wrap_line(line, direction: :left)

def determine_where_to_break_line(line, args)
direction = args.fetch(:direction)
index = TERMINAL_WIDTH
index = Shoulda::Matchers::WordWrap::TERMINAL_WIDTH
offset = OFFSETS.fetch(direction)

while line[index] !~ /\s/ && (0...line.length).cover?(index)
Expand Down
31 changes: 31 additions & 0 deletions spec/support/unit/helpers/application_configuration_helpers.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
module UnitTests
module ApplicationConfigurationHelpers
def with_belongs_to_as_required_by_default(&block)
configuring_application(
::ActiveRecord::Base,
:belongs_to_required_by_default,
true,
&block
)
end

def with_belongs_to_as_optional_by_default(&block)
configuring_application(
::ActiveRecord::Base,
:belongs_to_required_by_default,
false,
&block
)
end

private

def configuring_application(config, name, value)
previous_value = config.send(name)
config.send("#{name}=", value)
yield
ensure
config.send("#{name}=", previous_value)
end
end
end
151 changes: 151 additions & 0 deletions spec/support/unit/matchers/match_against.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
module UnitTests
module Matchers
def match_against(object)
MatchAgainstMatcher.new(object)
end

class MatchAgainstMatcher
DIVIDER = ('-' * Shoulda::Matchers::WordWrap::TERMINAL_WIDTH).freeze

attr_reader :failure_message, :failure_message_when_negated

def initialize(object)
@object = object
@failure_message = nil
@failure_message_when_negated = nil
end

def and_fail_with(message)
@message = message.strip
self
end
alias_method :or_fail_with, :and_fail_with

def matches?(generate_matcher)
@positive_matcher = generate_matcher.call
@negative_matcher = generate_matcher.call

if positive_matcher.matches?(object)
!message || matcher_fails_in_negative?
else
@failure_message = <<-MESSAGE
Expected the matcher to match in the positive, but it failed with this message:

#{DIVIDER}
#{positive_matcher.failure_message}
#{DIVIDER}
MESSAGE
false
end
end

def does_not_match?(generate_matcher)
@positive_matcher = generate_matcher.call
@negative_matcher = generate_matcher.call

if negative_matcher.does_not_match?(object)
!message || matcher_fails_in_positive?
else
@failure_message_when_negated = <<-MESSAGE
Expected the matcher to match in the negative, but it failed with this message:

#{DIVIDER}
#{negative_matcher.failure_message_when_negated}
#{DIVIDER}
MESSAGE
false
end
end

def supports_block_expectations?
true
end

private

attr_reader :object, :message, :positive_matcher, :negative_matcher

def matcher_fails_in_negative?
if !negative_matcher.does_not_match?(object)
if message == negative_matcher.failure_message_when_negated.strip
true
else
diff_result = diff(
message,
negative_matcher.failure_message_when_negated.strip,
)
@failure_message = <<-MESSAGE
Expected the negative version of the matcher not to match and for the failure
message to be:

#{DIVIDER}
#{message.chomp}
#{DIVIDER}

However, it was:

#{DIVIDER}
#{negative_matcher.failure_message_when_negated}
#{DIVIDER}

Diff:

#{Shoulda::Matchers::Util.indent(diff_result, 2)}
MESSAGE
false
end
else
@failure_message =
'Expected the negative version of the matcher not to match, ' +
'but it did.'
false
end
end

def matcher_fails_in_positive?
if !positive_matcher.matches?(object)
if message == positive_matcher.failure_message.strip
true
else
diff_result = diff(
message,
positive_matcher.failure_message.strip,
)
@failure_message_when_negated = <<-MESSAGE
Expected the positive version of the matcher not to match and for the failure
message to be:

#{DIVIDER}
#{message.chomp}
#{DIVIDER}

However, it was:

#{DIVIDER}
#{positive_matcher.failure_message}
#{DIVIDER}

Diff:

#{Shoulda::Matchers::Util.indent(diff_result, 2)}
MESSAGE
false
end
else
@failure_message_when_negated =
'Expected the positive version of the matcher not to match, ' +
'but it did.'
false
end
end

def diff(expected, actual)
differ.diff(expected, actual)[1..-1]
end

def differ
@_differ ||= RSpec::Support::Differ.new
mcmire marked this conversation as resolved.
Show resolved Hide resolved
end
end
end
end
Loading