Inspect Network Traffic in Capybara Using the Poltergeist Driver

DZone 's Guide to

Inspect Network Traffic in Capybara Using the Poltergeist Driver

In this post, we learn how to inspect network traffic of any page and validate its response values using these handy tools.

· Web Dev Zone ·
Free Resource

Ever tried inspecting the network traffic of any page and validating its response values? It's possible in Capybara if you are using the Poltergeist driver.

The Poltergeist driver is a PhantomJS driver for Capybara. It runs your tests in headless mode.

Network Tab in Developer Tools

If you are stuck up with any issues in any of the pages, you can open your dev tools and check the console errors or network traffic to understand the issue. This works if you are working on any browser.

Dev tools

What if You Are Running Your Capybara Tests?

All you need to do is add the below code:


The above line will give you all network calls made during the page load with its headers that are difficult to read/manage.

Let's say you only want the list of URLs and their corresponding status. Just add two more lines of code as shown below:

page.driver.network_traffic.each do |request|
    request.response_parts.uniq(&:url).each do |response|
        puts "\n URL #{response.url}: \n Status #{response.status}"

The above code will give you the below output:

Image title

Get Response Headers

Suppose you want to get all the response headers of a page, the code looks like what I've got below:


Image title

You can also get the value of a specific header from the list. For example, if you want to validate the 'cache-control' header.


What Other Things Can We Do?

  • Check for any missing request/response strings.

  • Check for any 404s or any other errors in the page.

Code to Register Your Poltergeist Driver in Capybara

options = {}
Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app, options)
Capybara.javascript_driver = :poltergeist
network traffic ,capybara ,ruby ,phantomjs ,web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}