如何在Ruby on Rails中测试黄瓜确认弹出窗口

时间:2019-04-12 19:49:51

标签: ruby-on-rails selenium cucumber capybara

我正在尝试通过Cucumber和Capybara在Ruby on Rails中测试我的应用程序的功能:当您单击“删除”按钮时,会出现一个确认消息: 确定吗?”然后应该单击“确定”。

起初我只是尝试

Given('I accept the popup') do
  click_button('OK')
end

然后黄瓜抛出错误:

Unable to find button "OK" (Capybara::ElementNotFound)

然后我尝试:

Given('I accept the popup') do
  page.driver.browser.switch_to.alert.accept
end
How to test a confirm dialog with Cucumber?中所述的

黄瓜抛出此错误:

undefined method `switch_to' for #<Capybara::RackTest::Browser:0x0000000009241c20> (NoMethodError)

然后我尝试在“ test.feature”中的场景之前添加“ @javascript”,例如:

@javascript
Scenario: Admin can manage scales
  Given I am on Scales page
  Given I destroy a scale
  Given I accept the popup
  Then I should see "Scale deleted"

然后黄瓜抛出错误:

Unable to find Mozilla geckodriver. Please download the server from https://github.com/mozilla/geckodriver/releases and place it somewhere on your PATH. More info at https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver.

我很困惑。我的环境配置是否错误?

我的宝石文件:

group :test do
  gem 'shoulda-matchers'
  gem 'simplecov', :require => false
  gem 'rails-controller-testing', '1.0.2'
  gem 'minitest-reporters', '1.1.14'
  gem 'guard', '2.13.0'
  gem 'guard-minitest', '2.4.4'
  gem 'capybara'
  gem 'launchy'
  gem 'selenium-webdriver'
  gem 'cucumber-rails', :require => false
  gem 'cucumber-rails-training-wheels'
end

我的web_steps.rb:

require 'uri'
require 'cgi'
require 'selenium-webdriver'

1 个答案:

答案 0 :(得分:0)

当使用不支持JS的驱动程序(RackTest)进行测试时,显然您无法测试JS触发的系统模式。通过在测试中添加@javascript标记,您已使Capybara转换为使用支持JS的驱动程序(硒驱动程序)。

您遇到的下一个错误是不言自明的-您的系统中未安装geckodriver,硒无法与Firefox通讯-如果您已配置驱动程序以与Chrome通讯它需要chromedriver。安装它们的最简单方法是将webdrivers添加到测试gem-https://github.com/titusfortner/webdrivers#usage

解决了这些问题之后,就需要编写步骤,这样它们才能最终运行代码

page.accept_confirm do
  click_button('delete') # The action that causes the confirm modal to appear
end

如果您还想以确认模式验证消息,则为

page.accept_confirm "Are you sure? do
  click_button('delete')
end