用水豚将文件附加到不可见的元素中

问题描述

我从capybaracucumberwebdriver开始,我承担了测试图像字段上传的任务。

因此,我模拟了一个可以学习的运输环境,它可以正常运行,但是,我需要保留元素“隐藏”,而且我不知道水豚是否有任何方法可以选择它。

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

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)

解决方法

如果要使文件输入元素不可见,则必须使用户可以使用一些可见元素进行交互,这又将触发文件输入文件的选择。在这种情况下,最好的解决方案是使用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)

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

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