水豚无法找到输入标签 CSS 元素

Capybara unable to find input tag CSS element

我正在尝试使用水豚查找 CSS 元素,但 RSpec 一直返回无法找到元素。我尝试使用 id、class 和 name.

HTML(使用检查元素)

<input class="new_photo_upload_entry" type="file" name="photo_upload_entry[upload]" id="photo_upload_entry_upload">

steps.rb 文件

expect(page).to have_css('#photo_upload_entry_upload')
expect(page).to have_css('.new_photo_upload_entry')
expect(page).to have_css('input[name="photo_upload_entry[upload]"]')

运行黄瓜特征结果:

expected to find css "#photo_upload_entry_upload" but there were no matches. Also found "", which matched the selector but not all filters. (RSpec::Expectations::ExpectationNotMetError)

expected to find css ".new_photo_upload_entry" but there were no matches (RSpec::Expectations::ExpectationNotMetError)

expected to find css "input[name=\"photo_upload_entry[upload]\"]" but there were no matches. Also found "", which matched the selector but not all filters. (RSpec::Expectations::ExpectationNotMetError)

由于您要查找的是文件元素,因此它很可能已隐藏在页面上(因此不同的元素可以在不同的浏览器中具有相同的样式)。这在大多数 JS 文件上传帮助程序库中都很常见。如果它在页面上实际上不可见,而您只是想确认它存在于页面源代码中,您可以将 visible: false 作为选项传递

expect(page).to have_css('#photo_upload_entry_upload', visible: false)

如果您接下来要调用 #attach_file 来上传文件,则需要使用 execute_script(...) 修改元素的 css 以使其可见在将文件附加到它之前。

另一个选项是该元素实际上不在页面上(因为如果元素存在且可见,您的所有 3 个查找器都应该匹配该元素)。您可以检查 page.html 以查看水豚实际使用的页面。