如何使用Capybara和Dropzone.js测试上传文件? [英] How do you test uploading a file with Capybara and Dropzone.js?
问题描述
我已将 Dropzone.js 插件用于拖放文件上传。
I've switched to using the Dropzone.js plugin for drag-and-drop file uploads. How can I write a Capybara test to ensure this functionality keeps on working?
以前我有一个带有输入文件元素的模板:
Previously I had a template with an input file element:
<input type="file" name="attachments">
测试很简单:
When(/^I upload "([^"]*)"$/) do |filename|
attach_file("attachments", File.expand_path(filename))
# add assertion here
end
但是,此操作不再有效,因为Dropzone无效
However this no longer works because Dropzone doesn't have a visible file input.
推荐答案
要解决此问题,请模拟放置事件以触发将附件拖放到Dropzone上。您的步骤定义的函数:
To solve this, simulate a drop event to trigger dropping an attachment onto Dropzone. First add this function to your step definition:
# 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 类。
NOTE: You need to have jQuery loaded, and the Dropzone element requires the dropzone class.
这篇关于如何使用Capybara和Dropzone.js测试上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!