Skip to content

Instantly share code, notes, and snippets.

@will
Created July 10, 2011 01:09
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 will/1074119 to your computer and use it in GitHub Desktop.
Save will/1074119 to your computer and use it in GitHub Desktop.
Classy

Classy — Class Testing

   classy is simple
no setup or descriptions
    just equality

(ruby 1.9 only, probably)

test.rb

require './classy'

str = Classy "ruby string"
str.size == 11
str.size != 11
str.reverse == "what"

ary = Classy [3,1,2]
ary.size == 3
ary.size != 9
ary.sort == [1,2,3]
ary << 4 == [8]

output

$ ruby test.rb
.FF...F
Expected not 11, but it was 11
	from test.rb:5:in `<main>'

Expected "what", but it was "gnirts ybur"
	from test.rb:6:in `<main>'

Expected [8], but it was [3, 1, 2, 4]
	from test.rb:12:in `<main>'

7 tests, 4 passing, 3 failing
0.000182 seconds elapsed
module Classy
def Classy(obj)
TestClass.new(obj)
end
def self.included(klass)
Runner.start
end
class TestClass < BasicObject
def initialize(obj)
@obj = obj
end
def method_missing(method, *args, &blk)
TestResponse.new @obj.send(method, *args, &blk)
end
end
class TestResponse < Struct.new(:actual)
def ==(expected)
test expected, true
end
def !=(expected)
test expected, false
end
private
def test(expected, truth)
if (actual == expected) == truth
Runner.pass
else
Runner.fail actual, expected, caller, truth
end
end
end
module Runner
extend self
@@pass = 0
@@failures = []
def pass
print "."
@@pass += 1
end
def fail(actual, expected, source, truth)
print "F"
@@failures << "Expected #{'not ' unless truth}#{expected.inspect}, but it was #{actual.inspect}\n\tfrom #{source[1]}"
end
def start
@@start = Time.now
at_exit { finish }
end
def finish
@@failures.each {|f| puts; puts f }
puts "\n#{@@pass + @@failures.size} tests, #{@@pass} passing, #{@@failures.size} failing"
puts "#{Time.now - @@start} seconds elapsed"
end
end
end
include Classy
require "./classy"
class Adder
def initialize(a)
@a = a
end
def add(b)
@a + b
end
end
a = Classy Adder.new(4)
a.add(2) == 6
a.add(0) == 4
a.add(0) == 2
a.add(0) != 2
str = Classy "ruby string"
str.size == 11
str.size != 11
str.reverse == "what"
ary = Classy [3,1,2]
ary.size == 3
ary.size != 9
ary.sort == [1,2,3]
ary << 4 == [8]
@iain
Copy link

iain commented Jul 11, 2011

Very clever! I like it!

@jeffkreeftmeijer
Copy link

I really like how this doesn't have some assert method. Also, it's quite complete for its size. :)

@hgmnz
Copy link

hgmnz commented Aug 21, 2012

67 lines of not golf code!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment