Skip to content

Commit

Permalink
Fixes #179: Check that attributes are set properly when testing for m…
Browse files Browse the repository at this point in the history
…atches

* AllowValueMatcher's `matches?` should check that the attribute was actually set to the value passed to it
  • Loading branch information
mxie committed Mar 27, 2013
1 parent 0209b3e commit 5768a50
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 7 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
@@ -1,4 +1,6 @@
# HEAD
* `AllowValueMatcher` checks that the right value is used for attempts at
setting the attribute with it
* Assert `class_name` value on real class name for `AssociationMatcher`
* Correct the variable used for `validate_confirmation_of` matcher description

Expand Down
27 changes: 20 additions & 7 deletions lib/shoulda/matchers/active_model/allow_value_matcher.rb
Expand Up @@ -53,11 +53,7 @@ def strict

def matches?(instance)
@instance = instance
@values_to_match.none? do |value|
@value = value
@instance.send("#{@attribute}=", @value)
errors_match?
end
attributes_set_properly? && errors_match?
end

def failure_message_for_should
Expand All @@ -74,8 +70,25 @@ def description

private

attr_accessor :value

def errors_match?
has_messages? && errors_for_attribute_match?
@values_to_match.none? do |current_value|
set_attribute_on_instance(current_value)
has_messages? && errors_for_attribute_match?
end
end

def attributes_set_properly?
@values_to_match.all? do |current_value|
set_attribute_on_instance(current_value)
@instance.send(@attribute.to_sym) == current_value
end
end

def set_attribute_on_instance(current_value)
self.value = current_value
@instance.send("#{@attribute}=", current_value)
end

def has_messages?
Expand Down Expand Up @@ -108,7 +121,7 @@ def errors_match_string?

def expectation
includes_expected_message = expected_message ? "to include #{expected_message.inspect}" : ''
[error_source, includes_expected_message, "when #{@attribute} is set to #{@value.inspect}"].join(' ')
[error_source, includes_expected_message, "when #{@attribute} is set to #{value.inspect}"].join(' ')
end

def error_source
Expand Down
Expand Up @@ -79,6 +79,13 @@
end

context 'an attribute which must be included in an array' do
context 'given an attribute that does not accept strings' do
it 'allows an attribute to be set as an integer' do
validating_integer_inclusion(:in => [0,1,2]).
should ensure_inclusion_of(:attr).in_array([0,1,2])
end
end

it 'accepts with correct array' do
validating_inclusion(:in => %w(one two)).
should ensure_inclusion_of(:attr).in_array(%w(one two))
Expand Down Expand Up @@ -164,6 +171,12 @@
end
end

def validating_integer_inclusion(options)
define_model(:example, :attr => :integer) do
validates_inclusion_of :attr, options
end.new
end

def validating_inclusion(options)
define_model(:example, :attr => :string) do
validates_inclusion_of :attr, options
Expand Down

0 comments on commit 5768a50

Please sign in to comment.