# Cuprite - Headless Chrome driver for Capybara
## [Documentation](https://docs.rubycdp.com/docs/cuprite/introduction)
Cuprite is a pure Ruby driver (read as _no_ Selenium/WebDriver/ChromeDriver
dependency) for [Capybara](https://github.com/teamcapybara/capybara). It allows
you to run Capybara tests on a headless Chrome or Chromium. Under the hood it
uses [Ferrum](https://github.com/rubycdp/ferrum#index) which is high-level API
to the browser by CDP protocol.
## Install
Add this to your `Gemfile` and run `bundle install`.
``` ruby
group :test do
gem "cuprite"
end
```
In your test setup add:
``` ruby
require "capybara/cuprite"
Capybara.javascript_driver = :cuprite
Capybara.register_driver(:cuprite) do |app|
Capybara::Cuprite::Driver.new(app, window_size: [1200, 800])
end
```
If Chrome or Chromium cannot use its sandbox inside a container—for example,
because it runs as `root`—enable Ferrum's container mode:
```ruby
Capybara::Cuprite::Driver.new(app, dockerize: true)
```
The `dockerize` option requires Ferrum 0.17.2 or newer. With an older Ferrum
version, pass the browser option explicitly:
```ruby
Capybara::Cuprite::Driver.new(
app,
browser_options: { "no-sandbox" => nil }
)
```
Both approaches disable the browser's sandbox, so do not use them merely
because Docker is involved. Prefer running the browser as a non-root user with
a working sandbox when possible.
Since Cuprite uses [Ferrum](https://github.com/rubycdp/ferrum#examples) there
are many useful methods you can call even using this driver.
`page.driver.browser` is a `Ferrum::Browser`:
```ruby
browser = page.driver.browser
browser.mouse.move(x: 123, y: 456).down.up
```
For Selenium you better check your code for `manage` calls because it works
differently in Cuprite, see the documentation below.
## Customization
See the full list of options for
[Ferrum](https://github.com/rubycdp/ferrum#customization).
You can pass options with the following code in your test setup:
``` ruby
Capybara.register_driver(:cuprite) do |app|
Capybara::Cuprite::Driver.new(app, options)
end
```
`Cuprite`-specific options are:
* options `Hash`
* `:raise_on_unhandled_modal` (Boolean) - When set to `false`, output a warning. When set to `true`, raise
`Capybara::Cuprite::UnhandledModalError` instead. The dialog is always auto-accepted either way; the raise is
deferred and surfaces on the next command sent to the browser. In practice that's almost always the same action
that triggered the dialog (a click, `visit`, `evaluate_script`, ...), since a JS dialog blocks the page until
answered, so that action's own command is what was waiting. A dialog fired with nothing in flight (e.g. a bare JS
timer) only surfaces on whatever command runs next.
* `:url_blocklist` (Array) - array of regexes to match against requested URLs, alias `:url_blacklist`
* `:url_allowlist` (Array) - array of regexes to match against requested URLs, alias `:url_whitelist`
* `:emulate` (Symbol) - device from Chrome DevTools' list to emulate, e.g. `:iphone_16`, `:pixel_9`, `:ipad_mini`
* `:mobile` (Boolean) - emulate a mobile device: viewport meta tag and touch events
* `:scale_factor` (Numeric) - device scale factor to emulate
`emulate:` sets the device's `:window_size`, `:scale_factor`, `:mobile` and user agent, options passed explicitly
take precedence:
```ruby
Capybara.register_driver(:cuprite) do |app|
Capybara::Cuprite::Driver.new(app, emulate: :iphone_14)
end
```
## Debugging
You can put `page.driver.debug` or `page.driver.debug(binding)` in your test to pause it.
This will launch the browser where you can inspect the content.
```ruby
it "does something useful" do
visit root_path
fill_in "field", with: "value"
page.driver.debug(binding)
expect(page).to have_content("value")
end
```
In the middle of the execution Chrome will open a new tab where you can inspect
the content and also if you passed `binding` an `irb` or `pry` console will be
opened where you can further experiment with the test.
## Clicking/Scrolling
* `page.driver.browser.mouse.click(x:, y:)` Click a very specific area of the screen.
* `page.scroll_to(left, top)` Scroll to a given position.
* `element.send_keys(*keys)` Send keys to a given node.
## Request headers
Manipulate HTTP request headers with Ferrum:
``` ruby
page.driver.browser.headers.get # => {}
page.driver.browser.headers.set("User-Agent" => "Cuprite")
page.driver.browser.headers.add({ "Referer" => "https://example.com" })
page.driver.browser.headers.get # => { "User-Agent" => "Cuprite", "Referer" => "https://example.com" }
```
Notice that `set` will overwrite already set headers. You should use `add` 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.
## Network traffic
* `page.driver.browser.network.traffic` allows you to inspect network traffic (i.e., loaded resources) on the current page. It returns an array of `Ferrum::Network::Exchange` objects, each representing a network request/response exchange. You can query both the request and response details of each exchange.
```ruby
# Retrieve all network exchanges
network_traffic = page.driver.browser.network.traffic
# Access the first exchange
first_exchange = network_traffic.first
# Inspect the response of the first request
response = first_exchange.response
```
* `page.driver.browser.network.wait_for_idle` Natively waits for network idle
and returns `false` if there are still active connections after timeout.
Accepts the same options as
[`wait_for_idle`](https://github.com/rubycdp/ferrum#wait_for_idleoptions)
```ruby
page.driver.browser.network.wait_for_idle
page.driver.refresh
```
Please note that network traffic is not cleared when you visit new page. You can
manually clear the network traffic by calling
`page.driver.browser.network.clear(:traffic)` or `page.driver.reset!`
* `page.driver.browser.wait_for_reload` unlike `network.wait_for_idle` will wait until
the whole page is reloaded or the timeout passes. It's useful when you know
that for example after clicking autocomplete suggestion you expect page to be
reloaded, you have a few choices - put sleep or wait for network idle, but both
are bad. Sleep makes you wait longer or less than needed, network idle can
return earlier even before the whole page is started to reload. Here's the
rescue.
## Manipulating cookies
Use Ferrum's cookies to inspect and manipulate cookies:
```ruby
cookies = page.driver.browser.cookies
cookies.set(name: "stealth", value: "omg")
cookies["stealth"].value # => "omg"
cookies.all # => { "stealth" => # }
cookies.remove(name: "stealth")
cookies.clear
```
## Screenshot
Besides capybara screenshot method you can get image or PDF as Base64 with Ferrum:
```ruby
page.driver.browser.screenshot(format: :jpeg, full: true)
page.driver.browser.pdf(paper_width: 6, paper_height: 12)
```
## Authorization
* `page.driver.browser.network.authorize(user:, password:) { |request, _index, _total| request.continue }`
## Proxy
```ruby
Capybara::Cuprite::Driver.new(app, proxy: { host: "127.0.0.1", port: 8080, user: "user", password: "password" })
```
The proxy is passed to Chrome as a command-line flag when the browser starts.
When connecting to a remote browser with the `:url` option (browserless, Selenoid, etc.), Cuprite doesn't launch
Chrome and the proxy flag is never applied, so configure the proxy on the remote browser itself. The `user` and
`password` are still used to answer the proxy's authentication challenge.
The `bypass` option is a list of hosts that skip the proxy, so don't pass the host you want to go through it.
## URL Blocklisting & Allowlisting
Cuprite supports URL blocklisting, which allows you to prevent scripts from
running on designated domains:
```ruby
page.driver.browser.url_blocklist = %r{http://www.example.com}
```
and also URL allowlisting, which allows scripts to only run on designated
domains:
```ruby
page.driver.browser.url_allowlist = %r{http://www.example.com}
```
For legacy support, `url_blacklist=` and `url_whitelist=` continue to work respectively.
If you are experiencing slower run times, consider creating a URL allowlist of
domains that are essential or a blocklist of domains that are not essential,
such as ad networks or analytics, to your testing environment.
## License
The gem is available as open source under the terms of the
[MIT License](https://opensource.org/licenses/MIT).