Skip to content

Instantly share code, notes, and snippets.

@carllerche
Created July 30, 2009 19:47
Show Gist options
  • Save carllerche/158882 to your computer and use it in GitHub Desktop.
Save carllerche/158882 to your computer and use it in GitHub Desktop.
require "rubygems"
require "spec"
module MatcherComposition
include Spec::Matchers
def +(other_matcher)
# Build a new simple matcher that combines self and the other matcher
simple_matcher("#{description} and #{other_matcher.description}") do |given, matcher|
matcher.negative_failure_message = ""
# Check both matchers. On the first failure, set the combined matcher's
# failure_message to the failure_message of the matcher that just failed
[self, other_matcher].all? do |m|
success = m.matches?(given)
matcher.negative_failure_message << "\n#{m.negative_failure_message}"
unless success
matcher.failure_message = m.failure_message
next false
end
true
end
end
end
end
class Spec::Matchers::SimpleMatcher
include MatcherComposition
end
def be_multiple_of_2
simple_matcher("be multiple of 2") do |given, matcher|
matcher.failure_message = "expected #{given} to be a multiple of 2, but it wasn't"
matcher.negative_failure_message = "expected #{given} to NOT be a multiple of 2, but it was"
given % 2 == 0
end
end
def be_multiple_of_5
simple_matcher("be multiple of 5") do |given, matcher|
matcher.failure_message = "expected #{given} to be a multiple of 5, but it wasn't"
matcher.negative_failure_message = "expected #{given} to NOT be a multiple of 5, but it was"
given % 5 == 0
end
end
def be_multiple_of_7
simple_matcher("be multiple of 7") do |given, matcher|
matcher.failure_message = "expected #{given} to be a multiple of 7, but it wasn't"
matcher.negative_failure_message = "expected #{given} to NOT be a multiple of 7, but it was"
given % 7 == 0
end
end
def be_multiple_of_10
be_multiple_of_2 + be_multiple_of_5
end
def be_multiple_of_70
be_multiple_of_2 + be_multiple_of_10 + be_multiple_of_7
end
describe "awesomeness" do
it "works" do
20.should be_multiple_of_10
end
it "fails" do
5.should be_multiple_of_10
end
it "negative fails" do
20.should_not be_multiple_of_10
end
it "combines 3" do
70.should be_multiple_of_70
end
it "collects all failure messages" do
10.should be_multiple_of_70
end
it "collects all negative failure messages" do
140.should_not be_multiple_of_70
end
it "works inline as well" do
10.should be_multiple_of_2 + be_multiple_of_5
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment