Docker - Capybara - Selenium - Chrome

Docker + Capybara + Selenium Chrome Driver

If your Rails app needs extracting data from a website, or if you want to write tests for your features, you might think about a solution like  Capybara.  If you take a look at Capybara github homepage, Capybara can integrate with many drivers, the default one is rack_test, the lightest driver but it does not support executing javascript. There are many other good drivers like capybara-webkit and poltergeist to integrate capybara with phantomjs. I have tried poltergeist but I experienced many problems as listed on the poltergeist github homepage. Thus, I decided to give a try with other popular web driver selenium install with famous  chrome browser.

In this blog I will note some steps to have chrome driver setup together with your Rails inside your Docker as I guess using Docker to setup Rails is quite common now.

    1. Run Docker pull command
      docker pull selenium/standalone-chrome
    2. You need to add extra gem
      gem 'selenium-webdriver'
    3. You need another Docker container which hook to hub. You can do so by adding below code to docker-compose.yml
services:
  web:
    image: selenium/node-chrome:3.12.0-boron    
    depends_on:
      - hub
    environment:
      HUB_HOST: hub

  hub:
    image: selenium/hub:3.12.0-boron
    ports:
      - "4444:4444"
    # .....

Update your docker by

docker-compose build

How about your code? The important thing is that you need to tell Capybara to hook to hub in order to open chrome headless browser when registering driver

require 'selenium-webdriver'
# .....

def instantiate_session
        selenium_url = "http://hub:4444/wd/hub"

        Capybara.register_driver :chrome do |app|
          options = Selenium::WebDriver::Chrome::Options.new(
            args: %w[headless disable-gpu no-sandbox]
          )
          Capybara::Selenium::Driver.new(app, url: selenium_url, browser: :chrome, options: options)
        end

        @session = Capybara::Session.new(:chrome)
        @session.visit(https://google.com)

Have fun!

Published by

Colin Dao

I am a hardworking Rubyist in Hanoi, Vietnam

Leave a comment