Module: Capybara::Node::Actions

Defined in:
lib/dropybara.rb

Instance Method Summary collapse

Instance Method Details

#drop_file(locator, *args) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/dropybara.rb', line 10

def drop_file(locator, *args)
  element_id = "dropybara_input_#{rand(1000)}"

  driver.execute_script <<-JS
    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('id', '#{element_id}')
    document.body.appendChild(input);
  JS

  attach_file(element_id, *args).tap do
    driver.execute_script <<-JS
      var input = document.getElementById('#{element_id}');
      var target = document.querySelector('#{locator}');
      var data = new DataTransfer();
      data.files = input.files;
      data.items.add(input.files[0]);
      data.types = ['Files'];

      var event = new DragEvent('drop', {
        target: target,
        dataTransfer: data
      });
      target.dispatchEvent(event);

      document.body.removeChild(input);
    JS
  end
end