Created
October 7, 2011 15:30
-
-
Save Ptico/1270536 to your computer and use it in GitHub Desktop.
Rspec functioning principle
This file contains 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
# Core | |
class Object | |
def should(matcher) | |
puts matcher.match(self) | |
end | |
end | |
class Matcher | |
def initialize(expected, &block) | |
@expected = expected | |
@matcher = block | |
end | |
def match(value) | |
@matcher.call(@expected, value) | |
end | |
end | |
# Matchers | |
def eq(value) | |
Matcher.new(value) do |expected, given| | |
if expected != given | |
<<-EOF | |
expected: #{expected} | |
got: #{given} | |
EOF | |
else | |
"Equal" | |
end | |
end | |
end | |
def not_eq(value) | |
Matcher.new(value) do |expected, given| | |
if expected != given | |
"Not equal" | |
else | |
<<-EOF | |
expected not: #{expected} | |
got: #{given} | |
EOF | |
end | |
end | |
end | |
def contains(value) | |
Matcher.new(value) do |expected, given| | |
if given.include?(expected) | |
"Includes" | |
else | |
<<-EOF | |
#{given} not contains #{expected} | |
EOF | |
end | |
end | |
end | |
# Test | |
'hello'.should(eq('world')) | |
2.should eq(2) | |
(2).should not_eq(2) | |
(2 * 2).should not_eq(5) | |
[1, 2, 3].should contains(4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment