Class: ActiveSpec::Specifications::CollectionSpecification

Inherits:
AttributesSpecification show all
Defined in:
lib/active_spec/specifications/collection_specification.rb

Overview

Checks the values of one or more attributes for inclusion within a given collection. This is similar to the Rails validation macro validates_inclusion_of.

Example usage:

include ActiveSpec::Specifications

class ColorPicker
  def color
    'red'
  end
end

spec_one = CollectionSpecification.new(['red', 'yellow'], :color)
spec_two = CollectionSpecification.new(['green', 'yellow'], :color)
spec_one.satisfied_by?(ColorPicker.new) # returns true
spec_two.satisfied_by?(ColorPicker.new) # returns false

The equivalent of the Rails validates_exclusion_of validation macro can be implemented by wrapping a CollectionSpecification inside a NotSpecification decorator.

Instance Method Summary collapse

Constructor Details

#initialize(collection, *attributes) ⇒ CollectionSpecification

collection can be any object that responds to include?, such as Array and Range objects.



27
28
29
30
# File 'lib/active_spec/specifications/collection_specification.rb', line 27

def initialize(collection, *attributes)
  @collection = collection
  super(*attributes)
end

Instance Method Details

#satisfied_by?(object) ⇒ Boolean

Returns false if the object fails to respond to to any of the given attributes, or if any of the attribute values for the object are not in the specified collection.

Returns:

  • (Boolean)


35
36
37
38
39
40
# File 'lib/active_spec/specifications/collection_specification.rb', line 35

def satisfied_by?(object)
  attributes_satisfy? do |a|
    return false unless object.respond_to?(a)
    return false unless @collection.include?(object.send(a))
  end
end