Search code examples
capybaraphantomjspoltergeist

How do I use phantomjs uploadFile with Capybara and poltergeist?


I am trying to attach a file in my spec, but the capybara attach_file method does not work for me in poltergeist (it returns true but nothing gets attached). It does work in Selenium, but for other reasons I want to use poltergeist. I know that the phantomjs uploadFile method (http://phantomjs.org/api/webpage/method/upload-file.html) simulates a user interacting with the file dialog which is what I think I need to do. I cannot figure out how to use it though in my Capybara spec.

I am trying to use

def drop_files(files, css_selector)
  js_script = 'fileList = Array(); '
  files.count.times do |index|
    # Generate a fake input selector
    page.execute_script("if ($('#seleniumUpload#{index}').length == 0) { " \
                        "seleniumUpload#{index} = window.$('<input/>')" \
                        ".attr({id: 'seleniumUpload#{index}', type:'file'})" \
                        ".appendTo('body'); }")

    # Attach file to the fake input selector through Capybara
    attach_file("seleniumUpload#{index}", files[index], visible: false)
    # Build up the fake js event
    #
    js_script << "fileList.push(seleniumUpload#{index}.get(0).files[0]); "
  end

  js_script << "e = $.Event('drop'); "
  js_script << "e.dataTransfer = { files : fileList }; "
  js_script << "$('#{css_selector}').trigger(e);"

  # Trigger the fake drop event
  page.execute_script(js_script)
end

which comes from https://github.com/teampoltergeist/poltergeist/issues/342 and works in selenium. The user that posted that says he has it working in poltergeist though.


Solution

  • It turns out file uploading is currently broken on Phantomjs 2.0. I downgraded v1.9.8 and attach_file works now.