2011-10-27 23:34:14 +01:00
|
|
|
module Capybara::Poltergeist
|
|
|
|
class Client
|
2012-02-29 00:02:43 +00:00
|
|
|
PHANTOMJS_SCRIPT = File.expand_path('../client/compiled/main.js', __FILE__)
|
2012-06-27 22:19:06 +01:00
|
|
|
PHANTOMJS_VERSION = '1.6.0'
|
2012-02-29 00:02:43 +00:00
|
|
|
PHANTOMJS_NAME = 'phantomjs'
|
2012-01-27 17:31:21 +00:00
|
|
|
|
|
|
|
def self.start(*args)
|
|
|
|
client = new(*args)
|
|
|
|
client.start
|
|
|
|
client
|
|
|
|
end
|
2011-10-27 23:34:14 +01:00
|
|
|
|
2012-07-11 20:14:17 +01:00
|
|
|
attr_reader :pid, :port, :path, :window_size, :phantomjs_options
|
2012-07-11 20:05:10 +01:00
|
|
|
|
2012-07-11 20:25:17 +01:00
|
|
|
def initialize(port, options = {})
|
2012-07-11 20:05:10 +01:00
|
|
|
@port = port
|
2012-07-11 20:25:17 +01:00
|
|
|
@path = options[:path] || PHANTOMJS_NAME
|
|
|
|
@window_size = options[:window_size] || [1024, 768]
|
|
|
|
@phantomjs_options = options[:phantomjs_options] || []
|
2012-03-11 10:35:02 +00:00
|
|
|
|
|
|
|
pid = Process.pid
|
|
|
|
at_exit { stop if Process.pid == pid }
|
2011-10-27 23:34:14 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def start
|
2012-01-27 17:31:21 +00:00
|
|
|
check_phantomjs_version
|
2012-03-11 10:35:02 +00:00
|
|
|
@pid = Spawn.spawn(*command)
|
2011-10-27 23:34:14 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def stop
|
2012-02-29 13:51:11 +00:00
|
|
|
if pid
|
2012-02-29 18:15:28 +00:00
|
|
|
begin
|
|
|
|
Process.kill('TERM', pid)
|
|
|
|
Process.wait(pid)
|
|
|
|
rescue Errno::ESRCH, Errno::ECHILD
|
|
|
|
# Zed's dead, baby
|
|
|
|
end
|
|
|
|
|
2012-02-29 13:51:11 +00:00
|
|
|
@pid = nil
|
|
|
|
end
|
2011-10-27 23:34:14 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def restart
|
|
|
|
stop
|
|
|
|
start
|
|
|
|
end
|
2012-01-27 17:31:21 +00:00
|
|
|
|
2012-02-25 12:47:18 +00:00
|
|
|
def command
|
|
|
|
@command ||= begin
|
|
|
|
parts = [path]
|
2012-07-11 20:14:17 +01:00
|
|
|
parts.concat phantomjs_options
|
2012-02-25 12:47:18 +00:00
|
|
|
parts << PHANTOMJS_SCRIPT
|
|
|
|
parts << port
|
2012-07-11 20:05:10 +01:00
|
|
|
parts.concat window_size
|
2012-03-11 10:35:02 +00:00
|
|
|
parts
|
2012-02-25 12:47:18 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2012-01-27 17:31:21 +00:00
|
|
|
private
|
|
|
|
|
|
|
|
def check_phantomjs_version
|
|
|
|
return if @phantomjs_version_checked
|
|
|
|
|
|
|
|
version = `#{path} --version`.chomp
|
2012-02-29 11:44:05 +00:00
|
|
|
|
|
|
|
if $? != 0
|
|
|
|
raise PhantomJSFailed.new($?)
|
|
|
|
elsif version < PHANTOMJS_VERSION
|
2012-01-27 17:31:21 +00:00
|
|
|
raise PhantomJSTooOld.new(version)
|
|
|
|
end
|
2012-02-29 11:44:05 +00:00
|
|
|
|
2012-01-27 17:31:21 +00:00
|
|
|
@phantomjs_version_checked = true
|
|
|
|
end
|
2011-10-27 23:34:14 +01:00
|
|
|
end
|
|
|
|
end
|