Skip to content

Instantly share code, notes, and snippets.

@Ptico
Created October 7, 2011 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ptico/1270536 to your computer and use it in GitHub Desktop.
Save Ptico/1270536 to your computer and use it in GitHub Desktop.
Rspec functioning principle
# 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