I’m working on testing a Rails application with a headless browser for feature tests using RSpec along with a web drivers gem for acquiring the Chrome driver. Unfortunately, some team members do not have Chrome installed on their machines, nor do they plan to. Additionally, we want to avoid installing Chrome on our Jenkins server for running tests. Is there a way to perform headless browser testing without requiring the actual browser to be installed on the testing environment? I’ve seen mixed information about whether headless testing needs the browser installed, with some articles suggesting it’s unnecessary, while official documentation from Chrome and Firefox indicates otherwise. I’ve also explored Cuprite, which seems to eliminate the need for WebDriver, but appears to still rely on having Chrome present. Any advice?
It is indeed possible to run headless browser tests in Rails without having the actual browser installed on your local or CI environment. The requirement of not installing a web browser itself can be bypassed by using a virtualized or containerized runtime for the tests.
One popular solution is to leverage Docker to run your tests within a container that includes the desired headless browser setup. By using a Docker container, the specific browser version and dependencies are isolated, ensuring consistency across different environments without requiring installations on individual machines or servers.
Here's a brief example of how you can structure a Dockerfile
to run your Rails tests using headless Chrome:
FROM ruby:2.7
# Install dependencies
RUN apt-get update -qq \
&& apt-get install -y nodejs npm \
&& npm install -g yarn \
&& apt-get install -y chromium-driver
# Setup app directory
WORKDIR /app
COPY . /app
# Install gems and run tests
RUN bundle install
RUN yarn install
RUN RAILS_ENV=test bundle exec rspec
Ensure your Gemfile
includes the necessary testing gems such as rspec-rails
and capybara
configured to use Selenium and Headless Chrome. Here's a quick setup:
# Gemfile
gem 'rspec-rails'
gem 'capybara'
gem 'selenium-webdriver'
And configure Capybara to use Selenium with headless Chrome:
# spec_helper.rb or rails_helper.rb
Capybara.register_driver :headless_chrome do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome, options: Selenium::WebDriver::Chrome::Options.new(args: %w[headless disable-gpu]))
end
Capybara.javascript_driver = :headless_chrome
By using Docker, you can sidestep the need for individual installations and maintain a stable and reproducible environment across your development and CI pipelines.