首页 > 解决方案 > 使用 Rails 上的文件或图像执行 Rspec 的正确方法是什么?

问题描述

我正在做一个需要上传图像的应用程序,这些图像稍后将显示在另一个视图上,但到目前为止,我还没有找到通过使用 Rspec 和 Capybara 的功能来测试它的正确方法

这是要测试的代码

<%= f.label :photo, "Foto"%>
<%= f.file_field :photo%><br>

在此处输入图像描述

作为查看页面的用户,我想模拟添加照片或文件的操作,因此它将像这样显示

<dt>Foto</dt>
<dd><%= image_tag @applicant.photo %></dd>

标签: ruby-on-railsrspeccapybara

解决方案


使用 Capybara 时,您可以使用以下attach_file方法通过文件输入上传文件 - https://rubydoc.info/github/teamcapybara/capybara/Capybara/Node/Actions#attach_file-instance_method 该方法采用与文件输入字段匹配的定位器id、名称、占位符、相关标签文本等。您还可以传递一些其他更具体的选项(参见文档)。在您的情况下,这意味着任何

attach_file('applicant_photo', '/path/to/file/to/attach') # id
attach_file('applicant[photo]', '/path/to/file/to/attach') # name attribute
attach_file('Foto', '/path/to/file/to/attach') # associated label text

应该为你工作。从技术上讲,在只有一个可见文件输入字段的页面上,您也可以这样做

attach_file('/path/to/file/to/attach') # will use the only file input on page

attach_file当文件输入字段不可见并且标签被设置样式以提供更现代的 UI 但当前不适用于您的用例时,还具有块接受模式。


推荐阅读