首页 > 解决方案 > 使用 Capybara 在不可见元素中附加文件

问题描述

我从capybaracucumber和开始webdriver,我的任务是测试图像字段的上传。

所以我模拟了一个我可以学习的运输环境,它工作正常,但是我需要将元素“隐藏”,我不知道是否有任何方法可以让水豚选择它。

所以我的代码朝这个方向发展:

HTML

<input type="file" name="attach-file" style="display: none;">

水豚/黄瓜

addMedicine_page.attach_file('attach-file', 'assets/asset.jpg')

然而,它会导致Unable to find visible file field "attach-file" message that is not disabled (Capybara :: ElementNotFound)

标签: webdrivercucumbercapybara

解决方案


如果您要使文件输入元素不可见,则必须有一些可见元素可供用户交互,从而触发文件输入文件选择。在这种情况下,最好的解决方案是使用接受 from 的块attach_file

page.attach_file('assets/asset.jpg') do
  # perform whatever action the user would to trigger the file selection
  click_button 'Upload file'
end

如果你不能为你工作,你真的应该能够并且它最接近地复制用户的行为,因此使测试最有效,那么你可以使用该make_visible选项

page.attach_file('attach-file', 'assets/asset.jpg', make_visible: true)

这将暂时使文件输入可见,将文件附加到它,然后重新隐藏它。如果您的页面应用的标准 CSSmake_visible无法使输入可见,您可以设置要使用的 CSS 值的哈希值,而不是true

https://www.rubydoc.info/github/jnicklas/capybara/Capybara/Node/Actions#attach_file-instance_method


推荐阅读