重构capybara javascript dropzone测试



我试图多次调用dropzone水豚测试。但是,当我第二次调用它时,ID已经被使用了。我正在尝试随机化ID,以便它可以多次运行。

def drop_in_dropzone(file_path)
  page.execute_script <<-JS
    fakeFileInput = window.$('<input/>').attr(
      {id: 'fakeFileInput', type:'file'}
    ).appendTo('body');
  JS
  attach_file("fakeFileInput", file_path)
  page.execute_script("var fileList = [fakeFileInput.get(0).files[0]]")
  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

第二次调用时出错。

Failure/Error: attach_file("fakeFileInput", file_path)
Capybara::Ambiguous:
Ambiguous match, found 2 elements matching file field "fakeFileInput"

您当然可以为输入生成一个随机id号,但如果不存在,则只创建fakeFileInput可能更容易。只有当你不将输入用于任何其他目的时,这才会起作用,但看起来这就是你正在做的。

page.execute_script <<-JS
  fakeFileInput = fakeFileInput || window.$('<input/>').attr(
    {id: '#{fake_input_id}', type:'file'}
  ).appendTo('body');
JS

如果它已经存在,它不会再被创建,它只会被重用。

最新更新