Class: RubyDocTest::CodeBlock

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

Overview

A CodeBlock is a group of one or more ruby statements, followed by an optional result. For example:

>> a = 1 + 1
>> a - 3
=> -1

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(statements = [], result = nil) ⇒ CodeBlock

Returns a new instance of CodeBlock.


16
17
18
19
# File 'lib/code_block.rb', line 16

def initialize(statements = [], result = nil)
  @statements = statements
  @result = result
end

Instance Attribute Details

#passedObject (readonly)

Returns the value of attribute passed


14
15
16
# File 'lib/code_block.rb', line 14

def passed
  @passed
end

#resultObject (readonly)

Returns the value of attribute result


14
15
16
# File 'lib/code_block.rb', line 14

def result
  @result
end

#statementsObject (readonly)

Returns the value of attribute statements


14
15
16
# File 'lib/code_block.rb', line 14

def statements
  @statements
end

Instance Method Details

#actual_resultObject


55
56
57
# File 'lib/code_block.rb', line 55

def actual_result
  @statements.last.actual_result
end

#expected_resultObject


59
60
61
# File 'lib/code_block.rb', line 59

def expected_result
  @result.expected_result
end

#linesObject


63
64
65
66
# File 'lib/code_block.rb', line 63

def lines
  @statements.map{ |s| s.lines }.flatten +
  @result.lines
end

#pass?Boolean

Tests

doctest: Single statement with result should pass >> ss = [RubyDocTest::Statement.new([“>> a = 1”])] >> r = RubyDocTest::Result.new([“=> 1”]) >> cb = RubyDocTest::CodeBlock.new(ss, r) >> cb.pass?

> true

doctest: Single statement without result should pass by default >> ss = [RubyDocTest::Statement.new([“>> a = 1”])] >> cb = RubyDocTest::CodeBlock.new(ss) >> cb.pass?

> true

doctest: Multi-line statement with result should pass >> ss = [RubyDocTest::Statement.new([“>> a = 1”]),

RubyDocTest::Statement.new([">> 'a' + a.to_s"])]

>> r = RubyDocTest::Result.new([“=> 'a1'”]) >> cb = RubyDocTest::CodeBlock.new(ss, r) >> cb.pass?

> true

Returns:

  • (Boolean)

42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/code_block.rb', line 42

def pass?
  if @computed
    @passed
  else
    @computed = true
    @passed =
      begin
        actual_results = @statements.map{ |s| s.evaluate }
        @result ? @result.matches?(actual_results.last) : true
      end
  end
end