Capybara无法找到输入标签CSS元素

时间:2016-01-28 18:10:24

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

我试图使用capybara找到一个CSS元素,但RSpec一直在返回,无法找到元素。我尝试了id,class和name。

HTML(使用inspect元素)

<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)

1 个答案:

答案 0 :(得分:2)

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

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

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

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