首页 > 解决方案 > 如何让 capybara chrome 无头打开 sweetalert2 模态以进行 Rspec 测试

问题描述

我目前正在使用

selenium-webdriver 3.141.0 chromedriver-helper 2.1.0

gem 'rails-assets-sweetalert2',来源:' https://rails-assets.org ' gem 'sweet-alert2-rails'

使用 Rails 5.2

我的水豚设置:

RSpec.configure do |config| 
  config.before(:each, type: :system) do
    driven_by :rack_test 
  end
  config.before(:each, type: :system, js: true) do 
    driven_by :selenium_chrome_headless
  end 
end
require "capybara-screenshot/rspec"

#Use the following to set the screen size for tests
Capybara.register_driver :selenium_chrome_headless do |app|
  options = Selenium::WebDriver::Chrome::Options.new

  [
    "headless",
    "window-size=1280x1280",
    "disable-gpu" # https://developers.google.com/web/updates/2017/04/headless-chrome
  ].each { |arg| options.add_argument(arg) }

  Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end

我运行以下测试:

    require 'rails_helper'

    RSpec.describe 'deleting a proofread document using ajax', js: true do

      let(:job)  { create(:proofreading_job, title: 'Internal Job') }
      let(:user) { job.proofreader.user }

      it 'can delete a proofread document' do
        visit root_path
        click_on 'Login'
        fill_in  'Email', with: user.email
        fill_in  'Password', with: user.password
        click_on 'Sign In'
        click_on 'Dashboard'
        click_on 'Proofreading Jobs'
        click_on 'Current'
        click_on 'Internal Job'
        click_on 'Upload Proofread Document'
        attach_file(I18n.t('proofreader.proofread_document.upload'), Rails.root + 'spec/test_documents/proofread_document/1.docx' , make_visible: true)
        accept_alert do
           find_button('Upload', disabled: false).click
        end
        expect(page).to_not have_button('Delete')

     end
   end
 end

但是测试失败,Rspec 通知我:

 Capybara::ModalNotFound:
   Unable to find modal dialog

但是,我已经手动使用了网页,并且模式确实显示并正常工作。

如何让 Capybara Selenium Chrome Headless Driver 在测试中打开模态?

标签: seleniumcapybaraselenium-chromedriverrspec-rails

解决方案


accept_alert用于处理系统模式(浏览器在调用时默认创建的那些window.alert实际上并不向页面添加元素的模式)。Sweetalert2 是一个 JS 库,可将元素插入页面以创建更时尚的“模态”。您不使用accept_alert这些,您只需与它们交互,就好像它们是页面上的任何其他 HTML 元素一样。这将意味着类似的东西

....
attach_file(...)
click_button('Upload', disabled: false) # Not sure why you're passing `disabled: false` here since that's the default
within('.swal2-actions') { click_button('the text of the button to accept the "modal"') }
expect(page)....

更新:正如评论中发现的那样——这个问题的另一个原因是资产没有在 OPs 设置中被编译,所以 JS 根本没有触发。当在非无头模式下运行并且看到没有显示“模态”时,这将立即清楚。对此的修复取决于正在使用什么资产管道以及它是如何配置的,这超出了这个问题的范围。


推荐阅读