Poltergeist Documentation

repository·master·Indexed 25 days ago

https://github.com/teampoltergeist/poltergeist

Poltergeist is a Capybara driver that uses PhantomJS (version 1.8.1 or higher) to run web tests in a headless browser environment for Ruby applications. It provides features for capturing screenshots, manipulating HTTP request headers and cookies, inspecting network traffic, and executing arbitrary JavaScript. The driver supports remote debugging via the :inspector option and offers extensive configuration for window size, JS error handling, and URL whitelisting/blacklisting.

Tokens
6.5K
Snippets
9
Records
45
Agent score
82%

What's inside Poltergeist

  1. Customize Poltergeist driver configuration

    master

    You can customize how Capybara sets up the Poltergeist driver by registering it with a custom options hash. This is typically done in your test setup block.

    Supported options include:

    • :phantomjs (String): Custom path to the phantomjs executable.
    • :debug (Boolean): If true, logs debug output to STDERR.
    • :logger (Object): An object responding to puts for debug output.
    • :phantomjs_logger (IO): Where PhantomJS STDOUT (including console.log) is written. Defaults to STDOUT.
    • :timeout (Numeric): Seconds to wait for a response from PhantomJS. Defaults to 30.
    • :inspector (Boolean, String): Enables remote debugging.
    • :js_errors (Boolean): If false, JavaScript errors are not re-raised in Ruby.
    • :window_size (Array): Browser window dimensions, e.g., [1024, 768]. Defaults to [1024, 768].
    • :screen_size (Array): Dimensions used when Window#maximize is called. Defaults to [1366, 768].
    • :phantomjs_options (Array): Additional command line options for PhantomJS, e.g., ['--load-images=no'].
    • :extensions (Array): Array of JS files to preload into the browser.
    • :port (Fixnum): Communication port. Defaults to a random open port.
    • :host (String): PhantomJS host IP/name. Defaults to '127.0.0.1'.
    • :url_blacklist (Array): Array of strings to match against requested URLs to prevent script execution.
    • :url_whitelist (Array): Array of strings to match against requested URLs to restrict script execution.
    • :page_settings (Hash): PhantomJS web page settings.
    Capybara.register_driver :poltergeist do |app|
      Capybara::Poltergeist::Driver.new(app, options)
    end
  2. Install PhantomJS

    master

    Poltergeist requires PhantomJS (version 1.8.1 or higher). It has no other external dependencies like Qt or an X server.

    Mac

    • Homebrew: brew tap homebrew/cask && brew cask install phantomjs
    • MacPorts: sudo port install phantomjs
    • Manual: Download the macOS zip from the PhantomJS downloads page.

    Linux

    • Download the 32-bit or 64-bit binary.
    • Extract the tarball and copy bin/phantomjs into your PATH.
    • Warning: Do NOT use the phantomjs package from official Ubuntu repositories; it is incompatible with Poltergeist.

    Windows

    • Download the precompiled Windows binary.

    Manual Compilation (Last Resort)

    If binaries fail, you can build from source, but note that this requires building WebKit and will take a long time.

    1. Download the source tarball.
    2. Extract and enter the directory.
    3. Run ./build.sh.
  3. Install Poltergeist

    master

    To use Poltergeist as a Capybara driver, add the gem to your Gemfile and configure your test setup to use the :poltergeist driver.

    Note: Switching from :rack_test to :poltergeist means your application will run in a separate thread, which may affect transactional tests. Refer to the Capybara documentation regarding database setup and transactions.

    # In Gemfile
    gem 'poltergeist'
    
    # In test setup
    require 'capybara/poltergeist'
    Capybara.javascript_driver = :poltergeist
  4. How Poltergeist detects the inspector browser

    master

    The Capybara::Poltergeist::Inspector class attempts to automatically detect a compatible browser to open the inspector interface. It searches the system PATH for the following executable names in order:

    • chromium
    • chromium-browser
    • google-chrome
    • open (macOS)

    If no matching executable is found, calling open will raise a Capybara::Poltergeist::Error suggesting that you manually specify a browser using the :inspector configuration option.

  5. Troubleshoot MouseEventFailed errors

    master

    Poltergeist simulates 'proper' clicks by calculating coordinates and scrolling to the element. If an element is covered by another element, the click will fail.

    If you encounter MouseEventFailed errors:

    1. Take screenshots to see if the element is obscured.
    2. Enable :debug mode to see the exact coordinates Poltergeist is attempting to click.
    3. Workaround: If you cannot resolve the overlap, use a DOM click event instead of a physical click simulation:

    Instead of:

    click_button "Save"

    Use:

    find_button("Save").trigger('click')
  6. Configure Remote Debugging with :inspector

    master

    You can enable remote debugging by registering a custom driver with the :inspector => true option. This allows you to use page.driver.debug to pause tests and launch a browser with the WebKit inspector.

    Capybara.register_driver :poltergeist_debug do |app|
      Capybara::Poltergeist::Driver.new(app, :inspector => true)
    end
    
    # Capybara.javascript_driver = :poltergeist
    Capybara.javascript_driver = :poltergeist_debug
  7. Manipulate cookies

    master

    Poltergeist provides several methods to manage cookies:

    • page.driver.cookies: Returns a hash of cookies where keys are names and values are Cookie objects (providing methods like name, value, domain, path, secure?, httponly?, samesite, and expires).
    • page.driver.set_cookie(name, value, options = {}): Sets a cookie. Options include :domain, :path, :secure, :httponly, :samesite, and :expires (which must be a Time object).
    • page.driver.remove_cookie(name): Removes a specific cookie.
    • page.driver.clear_cookies: Clears all cookies.
  8. Manipulate HTTP request headers

    master

    Poltergeist allows you to manage HTTP headers for all subsequent requests in the session.

    • page.driver.headers: Returns the current headers hash.
    • page.driver.headers = { ... }: Overwrites all existing headers.
    • page.driver.add_headers(key, value): Adds new headers without overwriting existing ones.

    Temporary Headers: You can set headers that only apply to the initial request (and related 30x redirects) using add_header with permanent: false. To prevent headers from being sent on redirects, use permanent: :no_redirect.

    page.driver.headers # => {}
    page.driver.headers = { "User-Agent" => "Poltergeist" }
    page.driver.add_headers("Referer" => "https://example.com")
    
    # Temporary headers for initial request only
    page.driver.headers = { "User-Agent" => "Poltergeist" }
    page.driver.add_header("Referer", "http://example.com", permanent: false)
    visit(login_path)
    # Headers are now back to default/permanent state
  9. Inspect network traffic

    master

    You can inspect the resources loaded by the current page using page.driver.network_traffic. This returns an array of request objects. Each request object has a response_parts method containing data about the response chunks.

    • Blocked requests: Use page.driver.network_traffic(:blocked) to see requests blocked by a whitelist or blacklist.
    • Clearing traffic: Network traffic is not cleared automatically when visiting a new page. Use page.driver.clear_network_traffic or page.driver.reset to clear it manually.