查看https://gist.github.com/mars/6957187#gistcomment-3019727和其他几个地方,更改默认选项的方法似乎是用您自己的代码覆盖驱动程序注册。这是我的司机注册:
RSpec.configure do |config|
Capybara.register_driver :selenium_headless do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
browser_options = ::Selenium::WebDriver::Firefox::Options.new.tap do |opts|
opts.add_argument '-headless'
opts.add_argument '--window-size=1920,1080'
end
Capybara::Selenium::Driver.new(app, **{ :browser => :firefox, options_key => browser_options })
end
end
我知道这是有效的,因为窗口大小显然会传递给 Firefox:
root 1466 1449 0 00:47 pts/5 00:00:00 /root/.webdrivers/geckodriver --port=4444 --binary=/usr/bin/firefox
root 1469 1466 1 00:47 pts/5 00:00:04 firefox-esr --marionette -headless --window-size=1920,1080 -foreground -no-remote -profile /tmp/rust_mozprofileAPMJOb
但是,当我中断测试然后使用 save_and_open_screenshot
时,浏览器绝对不是 1920x1080:
General
Complete name : capybara-202106300047373170133175.png
Format : PNG
Format/Info : Portable Network Graphic
File size : 45.1 KiB
Image
Format : PNG
Format/Info : Portable Network Graphic
Format_Compression : Deflate
Width : 1 366 pixels
Height : 694 pixels
Color space : RGBA
Bit depth : 8 bits
Compression mode : Lossless
Stream size : 45.1 KiB (100%)
我不知道为什么浏览器的大小似乎不对。如果我手动调整页面大小,生成的保存图像工作正常:
[9] pry(#<RSpec::ExampleGroups::TheUserLoginAndAvatarArea::ClickingTheDropdownForTheUserProfile>)> page.driver.browser.manage.window.resize_to(1920,1080)
=> {"x"=>0, "y"=>0, "width"=>1920, "height"=>1080}
但重点是不必这样做。
我见过几个在 resize_to
中使用 before
的示例,但这也不是最佳选择。
关于为什么这不能按预期工作的任何想法?
编辑: 它实际上适用于 Chromium:
Capybara.register_driver :selenium_chrome_headless do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
browser_options = ::Selenium::WebDriver::Chrome::Options.new.tap do |opts|
opts.add_argument('--no-sandbox')
opts.add_argument('--window-size=1920,1080')
opts.add_argument('--headless')
opts.add_argument('--disable-gpu') if Gem.win_platform?
# Workaround https://bugs.chromium.org/p/chromedriver/issues/detail?id=2650&q=load&sort=-id&colspec=ID%20Status%20Pri%20Owner%20Summary
opts.add_argument('--disable-site-isolation-trials')
end
Capybara::Selenium::Driver.new(app, **{ :browser => :chrome, options_key => browser_options })
end