【问题标题】:Rspec with Capybara have_css matcher is not working带有 Capybara have_css 匹配器的 Rspec 不起作用
【发布时间】:2015-06-08 05:31:50
【问题描述】:

在 Cucumber 中,使用 Rspec 和 Capybara 我有一个测试来检查按钮是否有一个类。在这里

expect(@some_button).to have_css(".in-cart")

失败了,但是

@some_button['class']

返回

'btn product in-cart'

所以按钮肯定有“in-cart”类。

作为一项临时措施,我已将测试更改为;-

expect(@some_button['class']).to match /in-cart/

这显然是疯了。但是为什么要'have_css'或'has_css?为明显具有预期类的 DOM 元素返回 false?

还有 page.all('.in-cart') 包含按钮,所以 Capybara 肯定能找到。

顺便说一句,我还尝试了 'button.in-cart'、'in-cart'、expect (etc).to have_selector、expect(etc.has_selector?('.in-cart')).to be_truthy 和所有组合.

【问题讨论】:

  • 当你尝试expect(@some_button).to have_css("btn.product.in-cart")时会发生什么

标签: ruby-on-rails rspec cucumber capybara


【解决方案1】:

have_css 匹配器预计将应用于父容器而不是实际元素

# your view
<div id="container">
  <div class="in_cart product"></div>
</div>

# your step definition
parent = page.find('div#container')
expect(parent).to have_css(".in-cart")
# => returns true, as there is nested div.in_cart
expect('div#container div').to have_css(".in-cart")
# => returns false, as there is no such selector inside of the latter div

至于匹配确切对象的属性,您必须坚持简单的按键查询

element = page.find('div#container div')
element['class'].should include('in-cart')
expect(element['class']).to match /in-cart/

相同的逻辑适用于所有RSpecMatchers

【讨论】:

    【解决方案2】:

    在较新版本的 Capybara/Rspec 中,默认情况下,expect(page) 将查询整个页面以查找匹配项;但是,有时我们可能不希望这样,而是更愿意针对页面的特定类/区域。对于这些情况,使用within 缩小page 的上下文范围:

    within('.container') do
      expect(page).to have_css(".in-cart")
    end
    

    假设父类有一个类container Capybara 只会在这个元素内搜索。

    【讨论】:

      【解决方案3】:

      expect(page).to have_css('button.in-cart')

      【讨论】:

      • 是的,它会检查页面是否有一个带有类 in-cart 的按钮,这正是作者所说的他想要做的事情
      • 这看起来像您在整个页面中搜索任何带有.in-cart 类的按钮。我认为问题是关于检查 特定 按钮是否具有该类?
      猜你喜欢
      • 1970-01-01
      • 2013-10-31
      • 1970-01-01
      • 2021-08-26
      • 2012-04-16
      • 2015-01-16
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      相关资源
      最近更新 更多