简体   繁体   English

检查所有(隐藏)元素是否包含带有 Minitest/Capybara 的字符串

[英]Check if all (hidden) elements contain a string with Minitest/Capybara

I have a list of elements on a page (cards with comic books) and I want to test if all elements have the title containing a string (let's say "spiderman").我在页面上有一个元素列表(带有漫画书的卡片),我想测试是否所有元素的标题都包含一个字符串(比如说“蜘蛛侠”)。

<%= @comics.each do |comic| %>
  <div class="comic-card-text-box">
    <p class="comic-card-title"><%= comic.title %></p>
  </div>
<% end %>

Using Minitest/Capybara/Rails 7 , I'm trying to do something like this:使用Minitest/Capybara/Rails 7 ,我正在尝试做这样的事情:

test "displays search results" do
    login_as users(:user1)
    visit root_path

    fill_in "Search...", with: "spiderman"

    assert_selector ".comic-card-title" do |element|
      assert_match element, /spiderman/
    end
  end

And that's the failure I get:这就是我得到的失败:

expected to find visible css ".comic-card-title" but there were no matches. Also found "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", which matched the selector but not all filters.

I have 2 issues there that I'm confused about.我有两个问题,我很困惑。

  1. I am trying to check if an element contains a substring.我正在尝试检查一个元素是否包含 substring。 What if this element is hidden on the page (only by hovering it will appear)?如果这个元素隐藏在页面上(只有悬停它才会出现)怎么办?

  2. How to iterate between these elements to check if all of them have the substring?如何在这些元素之间迭代以检查它们是否都具有 substring?

Your elements aren't matching either visibility or the filter proc you're passing to assert_selector (don't use assert_match with Capybara elements).您的元素不匹配可见性或您传递给 assert_selector 的过滤器过程(不要将assert_match与 Capybara 元素一起使用)。 If that's because the elements need to be hovered over then you should really just hover over them.如果那是因为需要将元素悬停在上面,那么你真的应该只在它们上方使用 hover。 Also assert_selector just validates that at least one of the elements will match, not that all of them will.同样assert_selector只是验证至少有一个元素会匹配,而不是所有元素都会匹配。 From your questions I'm assuming the comic-card-text-box element is visible on the page (takes up some space) and that the comic-card-title element only becomes visible when you hover over the comic-card-text-box element.根据您的问题,我假设comic-card-text-box元素在页面上可见(占用一些空间),并且仅当您 hover over the comic-card-text-box时, comic-card-title元素才可见comic-card-text-box元素。 If that's the case then you'd want to do something like如果是这种情况,那么你会想做类似的事情

cards = all('.comic-card-text-box', minimum: 1) # specifying count: <expected count> rather than minimum would be better
cards.each do |card|
  card.hover
  assert_css(card, '.comic-card-title', text: 'spiderman')
end

If my assumptions about what exactly you're trying to do, and your sites behavior are wrong please clarify in your question.如果我对您正在尝试做什么的假设以及您的网站行为是错误的,请在您的问题中澄清。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM