From dc5daca58f976d3feaa959166c109a2ef691464f Mon Sep 17 00:00:00 2001 From: Jason Draper Date: Fri, 21 Sep 2012 10:53:18 -0400 Subject: [PATCH] Model must only allow values inside of array for EnsureInclusionOf --- .../active_model/ensure_inclusion_of_matcher.rb | 15 +++++++++++++-- .../ensure_inclusion_of_matcher_spec.rb | 10 ++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/lib/shoulda/matchers/active_model/ensure_inclusion_of_matcher.rb b/lib/shoulda/matchers/active_model/ensure_inclusion_of_matcher.rb index 222b1bda..b6f137a4 100644 --- a/lib/shoulda/matchers/active_model/ensure_inclusion_of_matcher.rb +++ b/lib/shoulda/matchers/active_model/ensure_inclusion_of_matcher.rb @@ -83,7 +83,7 @@ module Shoulda # :nodoc: disallows_higher_value && allows_maximum_value elsif @array - if allows_all_values_in_array? && allows_blank_value? && allows_nil_value? + if allows_all_values_in_array? && allows_blank_value? && allows_nil_value? && disallows_outside_values? true else @failure_message = "#{@array} doesn't match array in validation" @@ -138,8 +138,19 @@ module Shoulda # :nodoc: def allows_maximum_value allows_value_of(@maximum, @high_message) end - end + def disallows_outside_values? + disallows_value_of(value_outside_of_array(@array)) + end + + def value_outside_of_array(array) + not_in_array = array.last.next + while array.include?(not_in_array) + not_in_array.next! + end + not_in_array + end + end end end end diff --git a/spec/shoulda/active_model/ensure_inclusion_of_matcher_spec.rb b/spec/shoulda/active_model/ensure_inclusion_of_matcher_spec.rb index 8a1bba13..832400db 100644 --- a/spec/shoulda/active_model/ensure_inclusion_of_matcher_spec.rb +++ b/spec/shoulda/active_model/ensure_inclusion_of_matcher_spec.rb @@ -1,6 +1,16 @@ require 'spec_helper' describe Shoulda::Matchers::ActiveModel::EnsureInclusionOfMatcher do + context "with no validations" do + before do + @model = define_model(:example, :attr => :string) do + end.new + end + + it "should reject an array which does not have a validator defined" do + @model.should_not ensure_inclusion_of(:attr).in_array(%w(Yes No)) + end + end context "an attribute which must be included in a range" do before do