A PhantomJS driver for Capybara
Poltergeist is a driver for Capybara. It allows you to run your Capybara tests on a headless PhantomJS browser. If you would like to run your tests on headless Chrome there's another project Cuprite claims to be compatible with Poltergeist.
If you're viewing this at https://github.com/teampoltergeist/poltergeist, you're reading the documentation for the master branch. View documentation for the latest release (1.18.1).
Questions should be posted on Stack Overflow, using the 'poltergeist' tag.
Bug reports should be posted on GitHub (and be sure to read the bug reporting guidance below).
Add this line to your Gemfile and run bundle install:
gem 'poltergeist'
In your test setup add:
require 'capybara/poltergeist'
Capybara.javascript_driver = :poltergeist
If you were previously using the :rack_test driver, be aware that
your app will now run in a separate thread and this can have
consequences for transactional tests. See the Capybara README for more
detail.
You need at least PhantomJS 1.8.1. There are no other external dependencies (you don't need Qt, or a running X server, etc.)
brew tap homebrew/cask && brew cask install phantomjssudo port install phantomjsDO NOT use phantomjs from the official Ubuntu repositories, since it doesn't
work well with poltergeist. More information
here.
Do this as a last resort if the binaries don't work for you. It will take quite a long time as it has to build WebKit.
./build.sh(See also the PhantomJS building guide.)
Poltergeist runs on MRI 1.9+, JRuby 1.9+ and Rubinius 1.9+. Poltergeist and PhantomJS are currently supported on Mac OS X, Linux, and Windows platforms.
Ruby 1.8 is no longer supported. The last release to support Ruby 1.8 was 1.0.2, so you should use that if you still need Ruby 1.8 support.
PhantomJS does not support ES6 features at the time of writing this
document. Setting js_errors to true can help determine if failing
tests require Polyfills, although a bug in PhantomJS can cause silent
failures if using ES6 features like let, const, etc.
There are no special steps to take. You don't need Xvfb or any running X server at all.
Travis CI, CircleCI, Codeship and Semaphore have PhantomJS pre-installed.
Depending on your tests, one thing that you may need is some fonts. If you're getting errors on a CI that don't occur during development then try taking some screenshots - it may well be missing fonts throwing things off kilter. Your distro will have various font packages available to install.
Poltergeist supports all the mandatory features for a Capybara driver, and the following optional features:
page.evaluate_script and page.execute_scriptpage.within_framepage.status_codepage.response_headerspage.save_screenshotpage.driver.render_base64(format, options)page.driver.scroll_to(left, top)page.driver.basic_authorize(user, password)element.send_keys(*keys)page.driver.set_proxy(ip, port, type, user, password)There are some additional features:
You can grab screenshots of the page at any point by calling
save_screenshot('/path/to/file.png') (this works the same way as the PhantomJS
render feature, so you can specify other extensions like .pdf, .gif, etc.)
Just in case you render pdf it's might be worth to set driver.paper_size= with
settings provided by PhantomJS in here
By default, only the viewport will be rendered (the part of the page that is in
view). To render the entire page, use save_screenshot('/path/to/file.png', :full => true).
You also have an ability to render selected element. Pass option selector with
any valid CSS element selector to make a screenshot bounded by that element
save_screenshot('/path/to/file.png', :selector => '#id').
If you need for some reasons base64 encoded screenshot you can simply call
render_base64 that will return you encoded image. Additional options are the
same as for save_screenshot except the first argument which is format (:png by
default, acceptable :png, :gif, :jpeg).
Sometimes its desirable to click a very specific area of the screen. You can accomplish this with
page.driver.click(x, y), where x and y are the screen coordinates.
If you use the :inspector => true option (see below), remote debugging
will be enabled.
When this option is enabled, you can insert page.driver.debug into
your tests to pause the test and launch a browser which gives you the
WebKit inspector to view your test run with.
You can register this debugger driver with a different name and set it as the current javascript driver. By example, in your helper file:
Capybara.register_driver :poltergeist_debug do |app|
Capybara::Poltergeist::Driver.new(app, :inspector => true)
end
# Capybara.javascript_driver = :poltergeist
Capybara.javascript_driver = :poltergeist_debug
You can manipulate HTTP request headers with these methods:
page.driver.headers # => {}
page.driver.headers = { "User-Agent" => "Poltergeist" }
page.driver.add_headers("Referer" => "https://example.com")
page.driver.headers # => { "User-Agent" => "Poltergeist", "Referer" => "https://example.com" }
Notice that headers= will overwrite already set headers. You should use
add_headers if you want to add a few more. These headers will apply to all
subsequent HTTP requests (including requests for assets, AJAX, etc). They will
be automatically cleared at the end of the test. You have ability to set headers
only for the initial request:
page.driver.headers = { "User-Agent" => "Poltergeist" }
page.driver.add_header("Referer", "http://example.com", permanent: false)
page.driver.headers # => { "User-Agent" => "Poltergeist", "Referer" => "http://example.com" }
visit(login_path)
page.driver.headers # => { "User-Agent" => "Poltergeist" }
This way your temporary headers will be sent only for the initial request, and related 30x redirects. All
subsequent request will only contain your permanent headers. If the temporary
headers should not be sent on related 30x redirects, specify permanent: :no_redirect.
Headers set with any of these methods will be set within all windows in the session, with the exception of temporary headers, which are only set within the current window.
You can inspect the network traffic (i.e. what resources have been
loaded) on the current page by calling page.driver.network_traffic.
This returns an array of request objects. A request object has a
response_parts method containing data about the response chunks.
You can inspect requests that were blocked by a whitelist or blacklist
by calling page.driver.network_traffic(:blocked). This returns an array of
request objects. The response_parts portion of these requests will always
be empty.
Please note that network traffic is not cleared when you visit new page.
You can manually clear the network traffic by calling page.driver.clear_network_traffic
or page.driver.reset
The following methods are used to inspect and manipulate cookies:
page.driver.cookies - a hash of cookies accessible to the current
page. The keys are cookie names. The values are Cookie objects, with
the following methods: name, value, domain, path, secure?,
httponly?, samesite, expires.page.driver.set_cookie(name, value, options = {}) - set a cookie.
The options hash can take the following keys: :domain, :path,
:secure, :httponly, :samesite, :expires. :expires should be a
Time object.page.driver.remove_cookie(name) - remove a cookiepage.driver.clear_cookies - clear all cookiesThere's an ability to send arbitrary keys to the element:
element = find('input#id')
element.send_keys('String')
or even more complicated:
element.send_keys('H', 'elo', :left, 'l') # => 'Hello'
element.send_keys(:enter) # triggers Enter key
Since it's implemented natively in PhantomJS this will exactly imitate user behavior. See more about sendEvent and PhantomJS keys
You can customize the way that Capybara sets up Poltergeist via the following code in your test setup:
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, options)
end
options is a hash of options. The following options are supported:
:phantomjs (String) - A custom path to the phantomjs executable:debug (Boolean) - When true, debug output is logged to STDERR.
Some debug info from the PhantomJS portion of Poltergeist is also
output, but this goes to STDOUT due to technical limitations.:logger (Object responding to puts) - When present, debug output is written to this object:phantomjs_logger (IO object) - Where the STDOUT from PhantomJS is written to. This is
where your console.log statements will show up. Default: STDOUT:timeout (Numeric) - The number of seconds we'll wait for a response
when communicating with PhantomJS. Default is 30.:inspector (Boolean, String) - See 'Remote Debugging', above.:js_errors (Boolean) - When false, JavaScript errors do not get re-raised in Ruby.:window_size (Array) - The dimensions of the browser window in which to test, expressed
as a 2-element array, e.g. [1024, 768]. Default: [1024, 768]:screen_size (Array) - The dimensions the window size will be set to when Window#maximize is called. Expressed
as a 2-element array, e.g. [1600, 1200]. Default: [1366, 768]:phantomjs_options (Array) - Additional command line options
to be passed to PhantomJS, e.g. ['--load-images=no', '--ignore-ssl-errors=yes']:extensions (Array) - An array of JS files to be preloaded into
the phantomjs browser. Useful for faking unsupported APIs.:port (Fixnum) - The port wNo open issues yet, or sync has not completed.