我已经切换到使用
Dropzone.js插件进行拖放文件上传.如何写一个Capybara测试来确保这个功能继续工作?
以前我有一个带有输入文件元素的模板:
<input type="file" name="attachments">
测试很简单:
When(/^I upload "([^"]*)"$/) do |filename| attach_file("attachments",File.expand_path(filename)) # add assertion here end
但是这不再适用,因为Dropzone没有可见的文件输入.
解决方法
为了解决这个问题,模拟一个drop甚至触发掉Dropzone附件.首先将此功能添加到您的步骤定义中:
# Upload a file to Dropzone.js def drop_in_dropzone(file_path) # Generate a fake input selector page.execute_script <<-JS fakeFileInput = window.$('<input/>').attr( {id: 'fakeFileInput',type:'file'} ).appendTo('body'); JS # Attach the file to the fake input selector attach_file("fakeFileInput",file_path) # Add the file to a fileList array page.execute_script("var fileList = [fakeFileInput.get(0).files[0]]") # Trigger the fake drop event page.execute_script <<-JS var e = jQuery.Event('drop',{ dataTransfer : { files : [fakeFileInput.get(0).files[0]] } }); $('.dropzone')[0].dropzone.listeners[0].events.drop(e); JS end
然后用:
When(/^I upload "([^"]*)"$/) do |filename| drop_in_dropzone File.expand_path(filename) # add assertion here end
注意:您需要加载jQuery,而Dropzone元素需要dropzone类.