Skip to content

Instantly share code, notes, and snippets.

@mig
Created January 26, 2011 23:31
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 mig/797752 to your computer and use it in GitHub Desktop.
Save mig/797752 to your computer and use it in GitHub Desktop.
class TestLibrary
@@stack = []
def self.stack
@@stack
end
def self.test_methods
public_instance_methods.grep(/^test/)
end
def self.should(name, &block)
method_name = "test_#{name.gsub(/\s/, '_')}"
define_method(method_name, &block)
(ancestors - [self]).each do |klass|
klass.test_methods.each {|method| send(:undef_method, method)} unless klass > TestLibrary
end
end
end
module Kernel
def context(name, &block)
sklass = TestLibrary.stack.last || TestLibrary
klass = Class.new(sklass)
sklass.const_set(name, klass)
klass.stack << klass
klass.class_eval(&block)
klass.stack.pop
klass
end
end
context "A" do
should("say hi bob") { true }
context "B" do
should("say hi sally") { true }
end
should("say hi ricky") { true }
end
p "Context A: #{TestLibrary::A.test_methods}"
p "Context B: #{TestLibrary::A::B.test_methods}"
# Output
#=> Context A: [:test_say_hi_bob, :test_say_hi_ricky]
#=> Context B: [:test_say_hi_sally, :test_say_hi_ricky]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment