ruby-on-rails - 使用 Rails 上的文件或图像执行 Rspec 的正确方法是什么?
问题描述
我正在做一个需要上传图像的应用程序,这些图像稍后将显示在另一个视图上,但到目前为止,我还没有找到通过使用 Rspec 和 Capybara 的功能来测试它的正确方法
这是要测试的代码
<%= f.label :photo, "Foto"%>
<%= f.file_field :photo%><br>
作为查看页面的用户,我想模拟添加照片或文件的操作,因此它将像这样显示
<dt>Foto</dt>
<dd><%= image_tag @applicant.photo %></dd>
解决方案
使用 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 但当前不适用于您的用例时,还具有块接受模式。
推荐阅读
- c# - 如何在检查器和资源管理器窗口中设置 Outlook 右侧窗格的最小宽度
- node.js - AdonisJS - 无法调用函数 csrfField
- android - 为什么我在运行我的 Android 项目时得到重复的类
- c - 读取一行并从文件中的矩阵中删除空格
- docker - 使用 Docker 在 Travis 中运行时,Zef 无法安装 JSON::Fast
- node.js - Express 不提供静态图片
- c# - 建立自己的链表;如何使链接仅通过列表本身更改?
- powershell - Measure -Sum -Property 不产生输出
- node.js - 防止在节点 readline 中输出空行
- php - 在 LARAVEL 中重新执行查询