Created
June 25, 2013 16:40
-
-
Save mcmire/5860047 to your computer and use it in GitHub Desktop.
Enumerable RSpec matchers
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 EnumerableMatchers | |
# RSpec already lets you do this: | |
# | |
# arr.should be_any {|item| item["foo"] == 2 } | |
# | |
# However, that's kind of unwieldy to say. So we add this matcher so we | |
# can say one of these alternatives instead: | |
# | |
# arr.should have_any {|item| item["foo"] == 2 } | |
# arr.should have_an {|item| item["foo"] == 2 } | |
# arr.should have_a {|hash| hash["foo"] == 2 } | |
# | |
# In English, that reads, "the array should have any item (an item, a hash) | |
# whose 'foo' value equals 2". | |
# | |
def have_any(&block) | |
HaveAny.new(block) | |
end | |
alias have_a have_any | |
alias have_an have_any | |
# RSpec already lets you do this: | |
# | |
# arr.should be_all {|item| item["foo"] == 2 } | |
# | |
# However, that doesn't read very well for certain cases. For instance: | |
# | |
# arr.should be_all {|item| item.is_a?(File) } | |
# | |
# This matcher lets you rewrite this as: | |
# | |
# arr.should have_all {|item| item.is_a?(File) } | |
# arr.should all_have {|item| item.is_a?(File) } | |
# | |
# In English, that reads, "the array should have all items where each item | |
# is a File", or "the array should all have an item where that item is a | |
# File". | |
# | |
def have_all(&block) | |
HaveAll.new(block) | |
end | |
alias all_have have_all | |
class HaveAny | |
def initialize(block) | |
@block = block | |
end | |
def matches?(enum) | |
enum.any?(&@block) | |
end | |
def failure_message_for_should | |
"expected Enumerable to have an item, but it didn't" | |
end | |
def failure_message_for_should_not | |
"expected Enumerable to not have an item, but it did" | |
end | |
def description | |
"should have an item" | |
end | |
end | |
class HaveAll | |
def initialize(block) | |
@block = block | |
end | |
def matches?(enum) | |
enum.all?(&@block) | |
end | |
def failure_message_for_should | |
"expected for all of the items to match a condition, but one of them didn't" | |
end | |
def failure_message_for_should_not | |
"expected for none of the items to match a condition, but one of them did" | |
end | |
def description | |
"should all match a condition" | |
end | |
end | |
end | |
RSpec.configure do |c| | |
c.include(EnumerableMatchers) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment