Skip to content

Commit

Permalink
Try next values in array only.
Browse files Browse the repository at this point in the history
If we can't find a valid next value outside of each item
in the array, throw a custom exception.
  • Loading branch information
drapergeek committed Oct 5, 2012
1 parent ddcd0f5 commit 1a71d16
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 8 deletions.
1 change: 1 addition & 0 deletions lib/shoulda/matchers/active_model.rb
Expand Up @@ -13,6 +13,7 @@
require 'shoulda/matchers/active_model/validate_confirmation_of_matcher'
require 'shoulda/matchers/active_model/validate_numericality_of_matcher'
require 'shoulda/matchers/active_model/allow_mass_assignment_of_matcher'
require 'shoulda/matchers/active_model/errors'


module Shoulda
Expand Down
22 changes: 14 additions & 8 deletions lib/shoulda/matchers/active_model/ensure_inclusion_of_matcher.rb
Expand Up @@ -83,7 +83,7 @@ def matches?(subject)
disallows_higher_value &&
allows_maximum_value
elsif @array
if allows_all_values_in_array? && allows_blank_value? && allows_nil_value? && disallows_outside_values?
if allows_all_values_in_array? && allows_blank_value? && allows_nil_value? && disallows_value_outside_of_array?
true
else
@failure_message = "#{@array} doesn't match array in validation"
Expand Down Expand Up @@ -137,16 +137,22 @@ def allows_maximum_value
allows_value_of(@maximum, @high_message)
end

def disallows_outside_values?
disallows_value_of(value_outside_of_array(@array))
def disallows_value_outside_of_array?
if value_outside_of_array
disallows_value_of(value_outside_of_array)
else
raise CouldNotDetermineValueOutsideOfArray
end
end

def value_outside_of_array(array)
not_in_array = array.last.next
while array.include?(not_in_array)
not_in_array.next!
def value_outside_of_array
found = @array.detect do |item|
!@array.include?(item.next)
end

if found
found.next
end
not_in_array
end
end
end
Expand Down
7 changes: 7 additions & 0 deletions lib/shoulda/matchers/active_model/errors.rb
@@ -0,0 +1,7 @@
module Shoulda # :nodoc:
module Matchers
module ActiveModel # :nodoc:
class CouldNotDetermineValueOutsideOfArray < RuntimeError; end
end
end
end
8 changes: 8 additions & 0 deletions spec/shoulda/active_model/ensure_inclusion_of_matcher_spec.rb
Expand Up @@ -12,6 +12,14 @@
end
end

context "where we cannot determine a value outside the array" do
it "should raise a custom exception" do
@model = define_model(:example, :attr => :string).new

expect { @model.should ensure_inclusion_of(:attr).in_array([""]) }.to raise_error Shoulda::Matchers::ActiveModel::CouldNotDetermineValueOutsideOfArray
end
end

context "an attribute which must be included in a range" do
before do
@model = define_model(:example, :attr => :integer) do
Expand Down

0 comments on commit 1a71d16

Please sign in to comment.