如何在 rails 项目中测试带有 rspec 的文件附件?
How to test a file attach with rspec in a rails project?
我在我的视图源中放了一个文件上传标签:
<%= form_tag(confirm_path, method: :post, multipart: true) do %>
<%= file_field_tag 'my_file' %>
<button type='submit'>Submit</button>
<% end %>
我想测试用户 select 是否有文件并单击提交按钮,然后重定向到下一页。这是我的规格来源:
require 'rails_helper'
feature 'MyTest', type: :feature do
describe 'File test' do
before do
visit index_path
end
it 'If select a file, then go to next page' do
attach_file 'my_file', my_real_file_path # I am sure this file exists
click_button 'Submit'
expect(page).to have_content('Confirm Page')
end
end
end
但是在我运行这个规格测试之后,它说:
Failure/Error: attach_file 'my_file', my_real_file_path
Capybara::ElementNotFound:
Unable to find file field 'my_file'
这通常是因为实际的文件字段被隐藏并被 "button" 或某些 JavaScript 驱动的界面覆盖,因此可以将其样式设置为在多个浏览器中看起来相同。如果是这种情况,您通常需要执行一些 JavaScript,使用 execute_script,以覆盖 css 隐藏文件字段的任何内容,使其在屏幕上可见,然后调用 attach_file
我在我的视图源中放了一个文件上传标签:
<%= form_tag(confirm_path, method: :post, multipart: true) do %>
<%= file_field_tag 'my_file' %>
<button type='submit'>Submit</button>
<% end %>
我想测试用户 select 是否有文件并单击提交按钮,然后重定向到下一页。这是我的规格来源:
require 'rails_helper'
feature 'MyTest', type: :feature do
describe 'File test' do
before do
visit index_path
end
it 'If select a file, then go to next page' do
attach_file 'my_file', my_real_file_path # I am sure this file exists
click_button 'Submit'
expect(page).to have_content('Confirm Page')
end
end
end
但是在我运行这个规格测试之后,它说:
Failure/Error: attach_file 'my_file', my_real_file_path
Capybara::ElementNotFound:
Unable to find file field 'my_file'
这通常是因为实际的文件字段被隐藏并被 "button" 或某些 JavaScript 驱动的界面覆盖,因此可以将其样式设置为在多个浏览器中看起来相同。如果是这种情况,您通常需要执行一些 JavaScript,使用 execute_script,以覆盖 css 隐藏文件字段的任何内容,使其在屏幕上可见,然后调用 attach_file