检查 Capybara::Node::Element 是否已被 jQuery.remove() 删除

Check if Capybara::Node::Element has been removed by jQuery.remove()

我正在尝试进行以下测试:

it 'remove item from cart' do
  visit cart_path
  button = page.find("a[href='/carts/#{item.id}/remove']")
  card = find_ancestor_with_class(button, '.card')
  button.click
  # check if card has been removed from page
end

此测试应该有效,因为以下 JS 从页面中删除了卡片:

$.ajax({
  url: link,
  method: "GET",
  success: function() {
    $('#alert-modal').modal('show');
    $(button).closest(".card").remove();
  }
});

如何验证 .card html 是否已从页面中删除?

检查页面上是否有内容不可见

expect(page).to have_no_css(".card")

expect(page).not_to have_css(".card")

所以整体变成了

visit cart_path
click_link(href: "/cars/#{item.id}/remove")    
expect(page).not_to have_css(".card")

仅当所有 .card 元素都被删除时才有效。如果页面上仍有其他 .card 元素,则检查您希望在卡片中的文本或卡片元素(id 等)上的其他 attribute/property,例如项目描述或显示为

的任何内容
expect(page).not_to have_css(".card", text: item.description)

如果您经常处理 .card 元素,您还可以编写自定义 Capybara 选择器以使内容更易于阅读,本地化 "card" 的 CSS 定义等

Capybara.add_selector :card do
  xpath do |content| 
    xp = XPath.css('.card')
    xp = xp[XPath.string.n.is(content)] unless content.nil?
    xp
  end
end

然后应该允许

expect(page).to have_no_selector(:card)
expect(page).to have_no_selector(:card, item.description)

等等