Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading file to specific folder using Capybara and Poltergeist driver

I am writing my acceptance tests using Capybara and Poltergeist driver.I need to validate the content of the CSV file downloaded.

  1. I tried various ways of rendering the content on the page itself instead of downloading it.
  2. Also tried changing the mime types, but it is not working.

Finally I want to settle down with the option of downloading the file in a specific folder and then read the CSV file using core ruby libraries.

In order to achieve this,when poltergeist driver clicks on download link then I want it to handle the pop-up and download the file directly in the given folder.

In Selenium's chrome and firefox drivers, I have option of configuring profiles to handle pop ups and configure download directory.

Is there any such option using poltergeist? Any information will be helpful.

like image 254
rupesh Avatar asked Apr 01 '13 07:04

rupesh


3 Answers

There is an ticket to support downloading files in PhantomJS/Poltergeist and there are one or two forks which claims that they made it to work somehow. See https://github.com/ariya/phantomjs/issues/10052

like image 76
wojtha Avatar answered Sep 30 '22 05:09

wojtha


I've had to do similar things in my rails app. My solution is using Javascript to make a XMLHttpRequest to the URL, downloading the file, returning the contents of the file back to Capybara, and using ruby to save the file somewhere on disk. Then in another step, I check the contents to the downloaded CSV file.

Here's the step definition for downloading the file:

Then /^I download the csv file$/ do
  page.execute_script("window.downloadCSVXHR = function(){ var url = window.location.protocol + '//' + window.location.host + '/file.csv'; return getFile(url); }")
  page.execute_script("window.getFile = function(url) { var xhr = new XMLHttpRequest();  xhr.open('GET', url, false);  xhr.send(null); return xhr.responseText; }")

  data = page.evaluate_script("downloadCSVXHR()")
  File.open(File.join(Rails.root, "tmp", "csv.data"), "w") { |f| f.write(data) }
end

Change the URL in the Javascript code to your CSV's location.

And finally, here's my step definition for validating the CSV file's contents:

And /^the contents of the downloaded csv should be:$/ do |contents|
  file = File.open(File.join(Rails.root, "tmp", "csv.data"), "r")
  file_contents = file.read
  file_contents.chop!
  file_contents.should == contents
end

Good luck. Hope this helps.

like image 35
Richard Avatar answered Oct 02 '22 05:10

Richard


This is not currently possible with Poltergeist.

I think you'd be better off writing a test for this CSV which doesn't use Capybara. (E.g. by using the built-in Rails integration testing stuff and parsing the response as a CSV.)

like image 33
jonleighton Avatar answered Sep 30 '22 05:09

jonleighton