Class: Docu::ExecutesExamples

Inherits:
Object
  • Object
show all
Defined in:
lib/docu/executes_examples.rb

Instance Method Summary collapse

Constructor Details

#initialize(kernel = Kernel) ⇒ ExecutesExamples

Returns a new instance of ExecutesExamples.



3
4
5
# File 'lib/docu/executes_examples.rb', line 3

def initialize kernel = Kernel
  @kernel = kernel
end

Instance Method Details

#execute(path) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/docu/executes_examples.rb', line 7

def execute path
  @kernel.puts "Executing Examples"
  errors = []
  successes = 0

  contents = File.read(path)

  contents.scan(/:example:((?:(?!^:end:).)*)/m).flatten.each do |example|
    if example =~ /#\s*=>\s*(.+)/
      expected = $1
      actual = eval(example).inspect

      if actual == expected
        successes += 1
      else
        errors << "Assertion does not match example. Expected \"#{actual}\" to equal \"#{expected}\""
      end
    end
  end

  @kernel.puts "#{errors.size} example(s) failed, #{successes} example(s) passed"

  if errors.any?
    errors.each do |error|
      @kernel.puts error
    end
    @kernel.exit 1
  else
    File.open(path.chomp(File.extname(path)), "w") do |file|
      file.write contents.gsub(":example:\n", "").gsub(":end:\n", "")
    end
  end
end