如何获取无头水豚铬以打开Sweetalert2模式进行Rspec测试

时间:2018-11-14 06:09:24

标签: selenium capybara selenium-chromedriver rspec-rails

我当前正在使用

selenium-webdriver 3.141.0 chromedriver-helper 2.1.0

gem'rails-assets-sweetalert2',来源:“ https://rails-assets.org” 宝石'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无头驱动程序以在测试中打开模式?

1 个答案:

答案 0 :(得分:0)

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根本没有触发。当以非无头模式运行并且看到没有“模式”显示时,这将立即变得清晰。该解决方案取决于正在使用的资产管道及其配置方式,这超出了此问题的范围。