Skip to content

Instantly share code, notes, and snippets.

@asaaki
Forked from peterc/README
Created July 18, 2011 18:50
Show Gist options
  • Save asaaki/1090313 to your computer and use it in GitHub Desktop.
Save asaaki/1090313 to your computer and use it in GitHub Desktop.
testrocket (origin by peterc)
TestRocket is a simple, tiny testing library for Ruby 1.9.
If => in a hash is a "hash rocket", then +-> and --> for tests should be
"test rockets"!
Simple syntax:
+-> { block that should succeed }
--> { block that should fail }
These tests would both pass:
+-> { 2 == 2 }
--> { 10 / 0 }
See the demonstration test "suite" for more.
Unique features (I hope):
* Unary plus/minus to denote expectations.
* Ability to fit the entire library into a single tweet/single line.
module TestRocket
def _test(a, b)
send((call rescue()) ? a : b)
end
def +@; puts _test :_pass, :_fail; end
def -@; puts _test :_fail, :_pass; end
def !@; puts _desc; end
def ~@; puts _pend; end
def _pass; ' #-> OK'; end
def _fail
file,line = source_location
content = (line-1..line+1).map{|i| ['L'+i.to_s,File.readlines(file)[i-1]].join("#{(line==i)?'*':':'} ")}.join
" #-> FAIL @ #{[file,line].join(':')}\n#{content}"
end
def _desc; "\nCASE \"" + call.to_s + "\": "; end
def _pend; "\nPENDING! " + call.to_s; end
end
Proc.send :include, TestRocket
# ===========================================================
# "DIE" - Simple dice simulator for us to test
class Die
attr_reader :sides
def initialize(sides = 6)
raise ArgumentError if sides < 2
@sides = sides
end
def roll
rand(@sides) + 1
end
end
# ===========================================================
# EXAMPLE TEST "SUITE" FOR "DIE"
#
# USAGE
# +-> { block that should succeed }
# --> { block that should fail }
# !-> { "description for output" }
# ~-> { "pending notice" }
!-> { "Create dies" }
+-> { Die.new(2) }
--> { Die.new(1) }
!-> { "Die should roll a value in given range" }
+-> { (1..6) === Die.new(6).roll }
+-> { Die.new.sides == 6 }
!-> { "Multiple die rolling without raising errors" }
+-> { die = Die.new(6)
1000.times { raise unless (1..6) === die.roll } }
+-> { die = Die.new(6)
1000.times { raise if die.roll.zero? } }
# These two tests will deliberately fail
!-> { "Failing tests" }
+-> { raise }
--> { !!true }
!-> { "Testing unaries in block context" }
+-> { !false }
--> { !true }
--> { !!nil }
~-> { "undefined test yet." }
@peterc
Copy link

peterc commented Jul 18, 2011

Impressed! I can't believe I didn't know you could redefine unary "!".. this might open up even more possibilities actually in terms of nesting, etc.

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