【问题标题】:Capybara unable to find input tag CSS elementCapybara 找不到输入标签 CSS 元素
【发布时间】:2016-01-28 18:10:23
【问题描述】:

我正在尝试使用 capybara 查找 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)

【问题讨论】:

    标签: ruby-on-rails-4 cucumber capybara bdd


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 编写 JS 脚本有些困难。 script = "document.getElementById(#photo_upload_entry_upload).style.visibility = 'visible';"
    • 这完全取决于它是如何隐藏的——你可能需要 display:block ,你可能需要 opactiy: 1 ,也许 z-index ,也许很重要!任何这些设置也需要。如果不确切知道应用了什么 CSS 来隐藏它,我们就无法知道如何取消隐藏它。
    • 有一个CSS是display:none,改为display:block。另外,在使用#attach_file时,我必须使用name,而不是idclass
    • attach_file 在设置文件之前调用find(:file_field, 'locator passed to attach_file') 来查找文件输入——这将获取附加到输入的标签文本、输入名称或输入(前面没有 # 因为它是 id 而不是 css 选择器)。它不需要上课,我猜你尝试了前面带有 # 的 id。 - 无论如何,只要你有它的工作一切都很好。