Created
April 1, 2010 17:09
-
-
Save jferris/352087 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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