Downloading file to specific folder using Capybara and Poltergeist driver

后端 未结 4 711
星月不相逢
星月不相逢 2020-12-14 02:47

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 rende
4条回答
  •  清歌不尽
    2020-12-14 03:14

    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.

提交回复
热议问题