【问题标题】:Rails Cucumber Testing AJAX using CapybaraRails Cucumber 使用 Capybara 测试 AJAX
【发布时间】:2018-06-06 00:32:13
【问题描述】:

我正在使用 Rspec、Capybara 和 Cucumber 来测试我网站的一项功能。本质上,我有一个时尚电子商务网站。我有显示所有商品的商店页面,当您单击特定商品时,它会将您带到该商品的详细信息页面,比如说一件毛衣。对于这件毛衣,作为购物者,您可以选择自己想要的尺寸和颜色。最后一个选项是您想要的选定尺寸和颜色的数量。但是,如果购物者选择不同的尺寸或颜色,我的 JS 代码会触发 AJAX 调用以更新总可用数量。因此,如果您从一件小的蓝色毛衣开始,然后将尺寸更改为中号,AJAX 调用将检索全部可用的中号蓝色毛衣。因此,如果有 10 个可用,那么数量的选择选项将从 1 变为 10。现在要测试此功能,我有以下内容:

# first create the items for the test db:
Given /^there are four total items and three unique item names$/ do
  create(:product, size: 'M', color: 'Black')
  create(:product, size: 'M', color: 'Black')
  create(:product, size: 'S', color: 'Black')
  create(:product, size: 'S', color: 'White')
  create(:product, size: 'S', color: 'White', available: false)
  create(:product, name: 'Alicia Dress', size: 'L', color: 'black', order: 3)
  create(:product, name: 'Cleopatra Dress', size: 'L', color: 'blue', order: 2)
end

然后我有我的黄瓜测试(注意起始选项是小而黑色,数量只有1,但是当你将尺寸选项更改为M时,它应该变为2,因为有两件M黑色外套) :

Scenario: If a shopper selects a different size or color
  Given the shopper is on the "shop" page
  When the shopper clicks on "Master Coat"
  And the shopper selects a size "M"
  Then the total quantity should change to "2"

还有我的测试步骤:

When /^the shopper selects a size "(.+)"$/ do |size|
  find('.select-size').find(:option, size).click
end

Then /^the total quantity should change to "(.+)"$/ do |quantity|
  expect(page).to have_css('option', :text => quantity)
end

注意,我省略了 Given 和 When 的步骤,因为我知道这些工作。我的主要问题是,在“并且购物者选择尺寸 M”之后,应该触发 AjAX 调用并更改数量,但在我的最后一步中,数量保持 1 并且不会更改为 2,正如它所假设的那样当我手动测试它时它会这样做。我的猜测是 AJAX 没有触发或者在最后一个测试步骤之后触发,因此在测试检查结果之前没有完成。

我的设置是否正确?如果是这样,我怎样才能让我的匹配器测试 AJAX 响应?我尝试了几件事,但没有成功。

【问题讨论】:

  • 您使用的网络驱动程序是什么?是硒吗?
  • web-driver 是 selenium,正确的。

标签: ruby-on-rails ruby rspec cucumber capybara


【解决方案1】:

我通常会使用带有@javascript 标记的 selenium 驱动程序来测试 Ajax 调用。

在你的 features/support/capybara.rb 中

Capybara.default_driver = :selenium

或者在场景上方试试@javascript标签

@javascript
Scenario: If a shopper selects a different size or color
Given the shopper is on the "shop" page
  When the shopper clicks on "Master Coat"
  And the shopper selects a size "M"
  Then the total quantity should change to "2"

【讨论】:

  • 这让我找到了解决方案。我发现Capybara使用的驱动是rack_test,不支持js。一旦我注册了另一个驱动程序,它就起作用了。感谢您的帮助
【解决方案2】:

也许您应该尝试选择带有.select_option 而不是.click 的选项。

When /^the shopper selects a size "(.+)"$/ do |size|
   find('.select-size').find(:option, size).select_option
end

(How to select option in drop down using Capybara)

【讨论】:

  • 我从 select_option 开始,然后从故障排除中单击。根据 Shani 的建议,我发现这是一个驱动程序问题,而不是我的代码中的任何问题。感谢您的回复。
猜你喜欢
  • 2014-09-18
  • 1970-01-01
  • 2013-05-19
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-08
相关资源
最近更新 更多