Skip to content

Instantly share code, notes, and snippets.

@jferris
Created April 1, 2010 17:09
Show Gist options
  • Select an option

  • Save jferris/352087 to your computer and use it in GitHub Desktop.

Select an option

Save jferris/352087 to your computer and use it in GitHub Desktop.
module CollectionMatchers
# Use with any existing matcher
# Example:
# posts.should all.be_published
# # Same as:
# posts.should_not be_empty
# posts.each { |post| post.should be_published }
def all
CollectionMatcher.new(self)
end
class CollectionMatcher
def initialize(example)
@example = example
end
def method_missing(matcher, *args, &block)
@matcher = matcher
@args = args
@block = block
self
end
def matches?(collection)
if collection.nil? || collection.empty?
@failure_message = "Can't test an empty collection"
return false
end
collection.all? do |item|
matcher = @example.send(@matcher, *@args, &@block)
if matcher.matches?(item)
@negative_failure_message = matcher.negative_failure_message
true
else
@failure_message = matcher.failure_message
false
end
end
end
attr_reader :failure_message, :negative_failure_message
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment