Browse files

Added spec/examples/log_buffer_example_spec.rb

  • Loading branch information...
1 parent 52beb46 commit a0dc63524e0da544d44919b7de1fd1e339a39b89 Kaoru Kobo committed Nov 18, 2010
Showing with 76 additions and 0 deletions.
  1. +10 −0 README.rdoc
  2. +66 −0 spec/examples/log_buffer_example_spec.rb
View
10 README.rdoc
@@ -113,6 +113,16 @@ for class method:
Please see spec: http://github.com/kaorukobo/rhook/blob/master/spec/rhook_spec.rb
+== Practical Example
+
+=== 1. Log Buffer
+
+Log Buffer allows you to capture any messages written to Logger and keep in buffer.
+
+For example, you can examine the target program's log messages in testing code.
+
+http://github.com/kaorukobo/rhook/blob/master/spec/examples/log_buffer_example_spec.rb
+
== ...
=== Note on Patches/Pull Requests
View
66 spec/examples/log_buffer_example_spec.rb
@@ -0,0 +1,66 @@
+require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
+
+describe "rhook examples" do
+ describe "log buffer (hack Logger)" do
+ require "logger"
+
+ # Captures any messages written to Logger and keep in buffer.
+ # You can read captured messages by LogBuffer#get
+ # or LogBuffer##pull ( also clears buffer ).
+ class LogBuffer
+ def initialize
+ @buf = ""
+ # Any log messages are passed to Logger#format_message. Hack it!!
+ Logger._rhook.hack(:format_message) do |inv|
+ result = inv.call
+ @buf << result
+ result
+ end
+ end
+
+ def clear
+ @buf = ""
+ end
+
+ def get
+ @buf
+ end
+
+ def pull
+ result = get()
+ clear()
+ result
+ end
+ end #/LogBuffer
+
+ # The example application to test.
+ # You cannot know whether it success or failed, (by return value or exception)
+ # ... it only logs.
+ class TargetApp
+ def initialize
+ @log = Logger.new(STDERR)
+ end
+
+ def success
+ @log.info "Success!"
+ end
+
+ def fail
+ @log.error "Failed!"
+ end
+ end
+
+ example "Use LogBuffer to write test" do
+ app = TargetApp.new
+
+ # start to capture log.
+ logbuf = LogBuffer.new
+
+ app.success
+ logbuf.pull.should match(/Success!/)
+
+ app.fail
+ logbuf.pull.should match(/Failed!/)
+ end
+ end
+end

0 comments on commit a0dc635

Please sign in to comment.