This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added spec/examples/log_buffer_example_spec.rb
- Loading branch information
Kaoru Kobo
committed
Nov 18, 2010
1 parent
52beb46
commit a0dc635
Showing
2 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |