rubycdp/cuprite
Tentang
Driver Chrome/Chromium headless untuk Capybara.
Alat pengembanganPertumbuhan bintang terukur
- dalam 24 jam
- 0
- dalam 7 hari
- 0
- dalam 15 hari
- +1
- dalam 1 bulan
- +3
Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.
README.md
AsliCuprite - Headless Chrome driver for Capybara
Documentation
Cuprite is a pure Ruby driver (read as no Selenium/WebDriver/ChromeDriver dependency) for Capybara. It allows you to run Capybara tests on a headless Chrome or Chromium. Under the hood it uses Ferrum which is high-level API to the browser by CDP protocol.
Install
Add this to your Gemfile and run bundle install.
group :test do
gem "cuprite"
end
In your test setup add:
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:
Capybara::Cuprite::Driver.new(app, dockerize: true)
It disables the browser's sandbox, so do not use it merely because Docker is involved. Prefer running the browser as a non-root user with a working sandbox when possible.
Since Cuprite uses Ferrum there
are many useful methods you can call even using this driver.
page.driver.current_page is the Ferrum page of the window Capybara is switched to:
page.driver.current_page.mouse.move(x: 123, y: 456).down.up
page.driver.current_page.network.traffic
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.
You can pass options with the following code in your test setup:
Capybara.register_driver(:cuprite) do |app|
Capybara::Cuprite::Driver.new(app, options)
end
Cuprite-specific options are:
- options
Hash:js_errors(Boolean) - re-raise JavaScript errors from the page asFerrum::JavaScriptError,falseby default:pending_connection_errors(Boolean) - raiseCapybara::Cuprite::PendingConnectionsErrorfromvisitwhen the page doesn't load in time,trueby default:screen_size(Array) - size used bymaximize_window,[1366, 768]by default:raise_on_unhandled_modal(Boolean) - When set tofalse, output a warning. When set totrue, raiseCapybara::Cuprite::UnhandledModalErrorinstead. 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:
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.
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.current_page.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:
page.driver.current_page.headers.get # => {}
page.driver.current_page.headers.set("X-Trace" => "1")
page.driver.current_page.headers.add({ "Referer" => "https://example.com" })
page.driver.current_page.headers.get # => { "X-Trace" => "1", "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.current_page.network.trafficallows you to inspect network traffic (i.e., loaded resources) on the current page. It returns an array ofFerrum::Network::Exchangeobjects, each representing a network request/response exchange. You can query both the request and response details of each exchange.
# Retrieve all network exchanges
network_traffic = page.driver.current_page.network.traffic
# Access the first exchange
first_exchange = network_traffic.first
# Inspect the response of the first request
response = first_exchange.response
page.driver.current_page.network.wait_idleNatively waits for network idle and returnsnilif there are still active connections after timeout. Accepts the same options aswait_idle
page.driver.current_page.network.wait_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.current_page.network.clear_traffic or page.driver.reset!
page.driver.current_page.await_navigation(watch: 1) { ... }runs the block and waits until the page it navigates to is loaded, or the timeout passes. A click already waits for the page it opens, but only for a navigation that starts withinFERRUM_NAVIGATION_WAIT, 0.1 seconds. Use it when the navigation starts later, for example when an autocomplete suggestion loads data first and only then opens the page. Sleep makes you wait longer or less than needed, and network idle can return before the navigation even started.
page.driver.current_page.await_navigation(watch: 1) { find(".suggestion").click }
Manipulating cookies
Use Ferrum's cookies to inspect and manipulate cookies:
cookies = page.driver.current_page.cookies
cookies.set(name: "stealth", value: "omg")
cookies["stealth"].value # => "omg"
cookies.to_a # => [#<Ferrum::Cookies::Cookie ...>]
cookies.remove(name: "stealth")
cookies.clear
Screenshot
Besides capybara screenshot method you can get image or PDF as Base64 with Ferrum:
page.driver.current_page.screenshot(format: :jpeg, full: true)
page.driver.current_page.pdf(paper_width: 6, paper_height: 12)
Authorization
page.driver.current_page.network.authorize(user:, password:) { |request, _index, _total| request.continue }
Proxy
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:
page.driver.url_blocklist = %r{http://www.example.com}
and also URL allowlisting, which allows scripts to only run on designated domains:
page.driver.url_allowlist = %r{http://www.example.com}
url_blacklist= and url_whitelist= are aliases of the same setters. Only one list can be set at a time.
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.
Sponsorship
If you or your company use Cuprite, please consider sponsoring its development. Sponsorship pays for maintenance, bug fixes and new features.
We don't sell advertising: no backlinks, SEO placements, banners or promotion of any kind in the README, documentation or website. Please don't email us about it.
License
The gem is available as open source under the terms of the MIT License.
Jelajahi proyek terkait
Memuat…