Module: Lab419::Mockify

Defined in:
lib/mockify.rb

Overview

Mockify has been created for Verify but can easily be used as a general purpose mocking technique for stdin and stdout. If you are not using Mockify with Verify you simply have to include the module yourself before calling #with_input and #with_output: E.g.

require 'mockify'
include Lab419::Mockify

Constant Summary collapse

AUTHOR =
"Robert Dober"
VERSION =
"0.3"

Instance Method Summary collapse

Instance Method Details

#with_input(ary, &blk) ⇒ Object

The provided block will be executed in an environement in which stdin is a StringIO object, created as a function of method parameter ary.

If ary is an IO object it will be used directly. If the ary parameter is a String a StringIO object is constructed by passing ary to the constructor. If it is an Array, the array will be joined with newline before being fed to StringIO constructor. All other arguments will raise an ArgumentError!



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/mockify.rb', line 90

def with_input ary, &blk
  ary = case ary
 when String
   StringIO::new ary
 when Enumerable
   StringIO::new ary.to_a.join( "\n" )
 when IO
   ary
 else
   raise ArgumentError, "Cannot make an IO out of #{ary.inspect}"
 end

  backup = $stdin
  $stdin = ary
  blk.call 
ensure
  $stdin = backup
end

#with_output(ary = nil, &blk) ⇒ Object

The provided block will be executed in an environement in which stdout is captured by a StringIO object. This is either a newly created StringIO object or a StringIO object provided as a parameter to with_output. with_output will return the StringIO that has been used, but it will also pass it to the block. Therefore verifications can be made inside the block. The returned object is the StringIO object already converted to an array of lines, but the object passed into the block is the StringIO object itself that still will change by each “writing” to stdout in the block. self.

e.g.
out = with_output do | o |
  puts 42
  verify target: "42\n", actual: o.string
  puts
end
verify do [ "42", "" ] == out


127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/mockify.rb', line 127

def with_output ary=nil, &blk

  ary ||= StringIO::new
  raise ArgumentError, "output mocking objects must be stringio's" unless StringIO === ary

  backup = $>
  $> = ary
  #instance_eval( &client )
  blk[ ary ] 
  ary.rewind
  ary.each_line.to_a
ensure
  $> = backup
end