Module: SpecUnit::ClassMethods

Defined in:
lib/spec-unit.rb

Instance Method Summary collapse

Instance Method Details

#context(name, &block) ⇒ Object



7
8
9
# File 'lib/spec-unit.rb', line 7

def context(name, &block)
  self.send :include, new_context(name, &block)
end

#new_context(name, &block) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/spec-unit.rb', line 11

def new_context(name, &block)
  context_module = new_context_module

  context_module.module_eval(&block)
  context_module.convert_specifications_to_tests(name.gsub(' ', '_'))
  context_module
end

#new_context_moduleObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/spec-unit.rb', line 19

def new_context_module
  Module.new do
    include SpecUnit

    def self.convert_specifications_to_tests(name)
      teardown, setup = unbound_teardown, unbound_setup
      specifications = self.instance_methods.select {|m| m.to_s =~ /^specify_/ || m.to_s =~ /^test_/}

      specifications.each do |spec|
        spec_method = unbound_method(spec)
        spec_name = spec.to_s.split(/^\w+?_/)[1]

        define_method(:"test_#{name}_#{spec_name}") do
          setup.bind(self).call if setup
          spec_method.bind(self).call
          teardown.bind(self).call if teardown
        end
      end
    end

    def self.unbound_setup
      unbound_method(:setup)
    end

    def self.unbound_teardown
      unbound_method(:teardown)
    end

    def self.unbound_method(meth)
      if self.instance_methods.include? meth.to_s
        unbound_meth = instance_method(meth)
        remove_method(meth) rescue module_where_defined(meth).module_eval { remove_method meth }
      end
      unbound_meth
    end

    def self.module_where_defined(meth)
      included_modules.detect { |mod| mod.method_defined?(meth) }
    end
  end
end