您好我是rails的初学者,当我尝试运行rspec capybara测试时会遇到一些问题。
require 'rails_helper'
describe "Upload Process", :type => :feature do
it "Can upload a file" do
visit new_document_path
page.attach_file('file', '/Users/yaomin/Desktop/my_travel_pic/uploadtest.jpg', visible: false)
click_button 'Upload'
page.should have_content("Uploadtest")
end
end
但是我收到了错误
Failures:
1) Upload Process Can upload a file
Failure/Error: attach_file('file', '/Users/yaomin/Desktop/my_travel_pic/uploadtest.jpg', visible: false)
Capybara::ElementNotFound:
Unable to find file field "file"
# /Users/yaomin/.rvm/gems/ruby-2.3.1/gems/capybara-2.13.0/lib/capybara/node/finders.rb:44:in `block in find'
# /Users/yaomin/.rvm/gems/ruby-2.3.1/gems/capybara-2.13.0/lib/capybara/node/base.rb:85:in `synchronize'
# /Users/yaomin/.rvm/gems/ruby-2.3.1/gems/capybara-2.13.0/lib/capybara/node/finders.rb:33:in `find'
# /Users/yaomin/.rvm/gems/ruby-2.3.1/gems/capybara-2.13.0/lib/capybara/node/actions.rb:256:in `attach_file'
# /Users/yaomin/.rvm/gems/ruby-2.3.1/gems/capybara-2.13.0/lib/capybara/session.rb:769:in `block (2 levels) in <class:Session>'
# /Users/yaomin/.rvm/gems/ruby-2.3.1/gems/capybara-2.13.0/lib/capybara/dsl.rb:52:in `block (2 levels) in <module:DSL>'
# ./spec/features/upload_test.rb:9:in `block (2 levels) in <top (required)>'
Finished in 0.40034 seconds (files took 1.99 seconds to load) 1 example, 1 failure
Failed examples:
rspec ./spec/features/upload_test.rb:5 # Upload Process Can upload a file
我的观看代码是
h1 Listing documents
table
thead
tr
th
th
th
tbody
- @documents.each do |document|
tr
td = link_to 'Show', document
td = link_to 'Edit', edit_document_path(document)
td = link_to 'Destroy', document, data: { confirm: 'Are you sure?' }, method: :delete
br
= link_to 'New Document', new_document_path
下面是新的文档视图
h1 New document
= render 'form'
= link_to 'Back', documents_path
- if @document.folder
= link_to "Back to '#{@document.folder.name}' Folder", browse_path(@document.folder)
- else
= link_to "Back", root_url
和我的表格部分
= form_for @document do |f|
- if @document.errors.any?
#error_explanation
h2 = "#{pluralize(@document.errors.count, "error")} prohibited this document from being saved:"
ul
- @document.errors.full_messages.each do |message|
li = message
= f.label :file
= f.file_field :file
- f.hidden_field :folder_id
= f.submit "Upload"
有关信息,我实际上可以手动上传文件,但我运行的上传测试失败。
提前感谢您的所有帮助:)
答案 0 :(得分:0)
传递给attach_file
的第一个参数需要是id,name或关联标签文本。在你的情况下,可能不是'文件'。您声明关联的标签文本是“选择文件”,所以可能类似
attach_file('Choose File', file_path)
是你想要的(如果没有实际的HTML,不可能确切地说出第一个参数应该是什么)。其他可能有效的事情是
attach_file('document_file', file_path) # match the elements id
attach_file('document[file]', file_path) # match the elements name
但同样,第一个参数可能略有不同,HTML将显示它们应该是什么。
文件输入常见的另一个问题是它们可能会被CSS隐藏(透明等),以便在浏览器中设置相同的样式。如果是这种情况并且您使用的是JS驱动程序,则可以使用类似
的内容attach_file('Choose File', file_path, make_visible: true)
将尝试使该字段可见,设置文件,然后恢复原始CSS。