Skip to content

Instantly share code, notes, and snippets.

@alloy
Created January 23, 2009 23:58
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 alloy/51272 to your computer and use it in GitHub Desktop.
Save alloy/51272 to your computer and use it in GitHub Desktop.
µspec & µmock: A 487 characters spec and mock framework on test/unit
require 'test/unit'
# from 'test' to 'mock' is the `it' code, from 'mock' onwards it's mocking.
module Test::Unit;T='test';class Failure;def long_display;"#{l=location;Array===l ?l[0]:l}\n#{message}".sub(T,'');end;end;$M={};class TestCase;def self.it(n,&b);define_method(T+n,&b)end;'mock';def m(m,n,v);$M[n]=[m,n,m.method(n),caller[0],v];eval"def m.#{n};m=$M['#{n}'];m[5]=true;m[4];end"end;def teardown;$M.map{|_,m|(class<<m[0];self;end).send(:define_method,m[1],m[2].to_proc);m}.map{|m|$M.delete(m[1]);add_failure("#{m[0].inspect} didn't receive :#{m[1]}",m[3])if !m[5]}end;end;end
if $0 == __FILE__
# Test case
class TestObject
def self.a_class_method
false
end
def an_instance_method
false
end
end
class MicroMock < Test::Unit::TestCase
it "should mock and unmock on a class method" do
m(TestObject, 'a_class_method', true)
assert !TestObject.a_class_method
teardown # unmock
assert !TestObject.a_class_method
end
it "should mock and unmock on an instance method" do
obj = TestObject.new
m(obj, 'an_instance_method', true)
assert obj.an_instance_method
teardown # unmock
assert !obj.an_instance_method
end
it "should assert that the method was actually called" do
obj = TestObject.new
m(obj, 'an_instance_method', true)
#obj.an_instance_method # if we don't call the method it's a failure
end
end
# 1:% ruby ~/Desktop/µspec-and-µmock.rb
# Loaded suite /Users/eloy/Desktop/µspec-and-µmock
# Started
# FF.
# Finished in 0.00827 seconds.
#
# 1) /Users/eloy/Desktop/µspec-and-µmock.rb:41:in `should assert that the method was actually called'
# #<TestObject:0x53d68> didn't receive :an_instance_method
#
# 2) /Users/eloy/Desktop/µspec-and-µmock.rb:25:in `should mock and unmock on a class method'
# <false> is not true.
#
# 3 tests, 3 assertions, 2 failures, 0 errors
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment