Skip to content

Commit

Permalink
Forward webkit_server's stdout to Ruby's stdout.
Browse files Browse the repository at this point in the history
This allows console.log() messages to be visible, and prevents
large numbers of console.log() calls from filling up webkit_server's pipe
which would block the process.
  • Loading branch information
FooBarWidget committed Aug 15, 2011
1 parent 82ae0c2 commit dc49e5f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
19 changes: 19 additions & 0 deletions lib/capybara/driver/webkit/browser.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'socket'
require 'thread'
require 'capybara/util/timeout'
require 'json'

Expand All @@ -8,6 +9,9 @@ class Browser

def initialize(options = {})
@socket_class = options[:socket_class] || TCPSocket
@stdout = options.has_key?(:stdout) ?
options[:stdout] :
$stdout
start_server
connect
end
Expand Down Expand Up @@ -79,6 +83,10 @@ def render(path, width, height)
def start_server
read_pipe, write_pipe = fork_server
@server_port = discover_server_port(read_pipe)
@stdout_thread = Thread.new do
Thread.current.abort_on_exception = true
forward_stdout(read_pipe)
end
end

def fork_server
Expand All @@ -100,6 +108,17 @@ def discover_server_port(read_pipe)
return unless IO.select([read_pipe], nil, nil, 10)
((read_pipe.first || '').match(/listening on port: (\d+)/) || [])[1].to_i
end

def forward_stdout(pipe)
while !pipe.eof?
line = pipe.readline
if @stdout
@stdout.write(line)
@stdout.flush
end
end
rescue EOFError
end

def connect
Capybara.timeout(5) do
Expand Down
9 changes: 9 additions & 0 deletions spec/browser_spec.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'spec_helper'
require 'stringio'
require 'capybara/driver/webkit/browser'

describe Capybara::Driver::Webkit::Browser do
Expand All @@ -22,5 +23,13 @@
new_browser.server_port.should_not == browser.server_port
end
end

it 'forwards stdout to the given IO object' do
io = StringIO.new
new_browser = Capybara::Driver::Webkit::Browser.new(:stdout => io)
new_browser.execute_script('console.log("hello world")')
sleep(0.5)
io.string.should == "hello world\n"
end

end
2 changes: 1 addition & 1 deletion spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
require File.join(spec_dir,"spec_helper")

require 'capybara/driver/webkit/browser'
$webkit_browser = Capybara::Driver::Webkit::Browser.new(:socket_class => TCPSocket)
$webkit_browser = Capybara::Driver::Webkit::Browser.new(:socket_class => TCPSocket, :stdout => nil)

Capybara.register_driver :reusable_webkit do |app|
Capybara::Driver::Webkit.new(app, :browser => $webkit_browser)
Expand Down

0 comments on commit dc49e5f

Please sign in to comment.