Skip to content
This repository has been archived by the owner on Nov 3, 2021. It is now read-only.

Commit

Permalink
Added spec/examples/log_buffer_example_spec.rb
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaoru Kobo committed Nov 18, 2010
1 parent 52beb46 commit a0dc635
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.rdoc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
66 changes: 66 additions & 0 deletions spec/examples/log_buffer_example_spec.rb
Original file line number Diff line number Diff line change
@@ -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.