Created
January 26, 2011 23:31
-
-
Save mig/797752 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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