使用Capybara和Poltergeist驱动程序将文件下载到特定文件夹

时间:2013-04-01 07:29:48

标签: capybara poltergeist

我正在使用Capybara和Poltergeist驱动程序编写验收测试。我需要验证下载的CSV文件的内容。

  1. 我尝试了各种方法在页面上呈现内容而不是下载它。
  2. 还尝试更改mime类型,但它无法正常工作。
  3. 最后,我想选择在特定文件夹中下载文件,然后使用核心ruby库读取CSV文件。

    为了实现这一点,当poltergeist驱动程序点击下载链接时,我希望它能够处理弹出窗口并直接在给定文件夹中下载文件。

    在Selenium的chrome和firefox驱动程序中,我可以选择配置配置文件来处理弹出窗口并配置下载目录。

    使用恶作剧者有没有这样的选择?任何信息都会有所帮助。

4 个答案:

答案 0 :(得分:23)

使用Poltergeist是不可能的,你可以检查标题。

 step 'I should get zipped file' do
    page.response_headers['Content-Disposition'].should include("filename=\"file.zip\"")
 end

但可以使用Chrome驱动程序以及最新版本的Firefox和Selenium Webdriver。不幸的是,它通过Selenium运行 - 即不是无头......请参阅此文章:http://collectiveidea.com/blog/archives/2012/01/27/testing-file-downloads-with-capybara-and-chromedriver/

我的方法 - 与我在使用Spinach和Rubyzip时略有不同:

将以下内容添加到 Gemfile

group :test do
  gem 'chromedriver-helper'  # for Chrome <= 28
  gem 'chromedriver2-helper' # for Chrome >= 29
  gem 'selenium-webdriver'
end

features / support / capybara.rb - 我在使用带有@javascript标记的情景时使用了使用Poltergeist,在使用@download标记的情景中使用了Chrome。

require 'spinach/capybara'
require 'capybara/poltergeist'
require 'selenium/webdriver'

# ChromeDriver 1.x, for Chrome <= 28 
Capybara.register_driver :chrome do |app|
  profile = Selenium::WebDriver::Chrome::Profile.new
  profile['download.default_directory'] = DownloadHelper::PATH.to_s
  args = ["--window-size=1024,768"]
  Capybara::Selenium::Driver.new(app, browser: :chrome, profile: profile, args: args)
end

# ChromeDriver 2.x, for Chrome >= 29 
Capybara.register_driver :chrome do |app|
  prefs = {
    download: {
      prompt_for_download: false,
      default_directory: DownloadHelper::PATH.to_s
    }
  }
  args = ['--window-size=1024,768']
  Capybara::Selenium::Driver.new(app, browser: :chrome, prefs: prefs, args: args)
end

# Tested with Firefox 27 and Selenium Webdriver 2.39
Capybara.register_driver :firefox do |app|
  profile = Selenium::WebDriver::Firefox::Profile.new
  profile['browser.download.dir'] = DownloadHelper::PATH.to_s
  profile['browser.download.folderList'] = 2 # 2 - save to user defined location
  profile['browser.helperApps.neverAsk.saveToDisk'] = 'application/zip'
  Capybara::Selenium::Driver.new(app, browser: :firefox, profile: profile)
end

Capybara.javascript_driver = :poltergeist # :webkit :selenium :poltergeist :chrome

Spinach.hooks.on_tag("javascript") do
  Capybara.current_driver = Capybara.javascript_driver
  Capybara.default_wait_time = 5
end

Spinach.hooks.on_tag("download") do
  Capybara.current_driver = :chrome # or :firefox
  Capybara.default_wait_time = 50
end

功能性/支撑性/ downloads.rb

module DownloadHelper
  TIMEOUT = 10
  PATH    = Rails.root.join("tmp/downloads")

  extend self

  def downloads
    Dir[PATH.join("*")]
  end

  def download_path
    wait_for_download
    downloads.first
  end

  def download_content
    wait_for_download
    File.read(download_path)
  end

  def wait_for_download
    Timeout.timeout(TIMEOUT) do
      sleep 0.1 until downloaded?
    end
  end

  def downloaded?
    downloads.any? && !downloading?
  end

  def downloading?
    downloads.grep(/\.crdownload$/).any?
  end

  def clear_downloads
    FileUtils.rm_f(downloads)
  end

end

Spinach.hooks.before_scenario do |scenario|
  DownloadHelper.clear_downloads
end

Spinach.hooks.after_scenario do
  DownloadHelper.clear_downloads
end

功能/ file_download.feature

Feature: File download
   As a user
   I want to be able to download my files

Background:
  Given I am logged in as a user
  And I have uploaded files in the system

@download
Scenario: Successfull download
  When I click on the download button
  Then I should get zipped files

features / steps / file_download.rb - 请注意,您无法使用page.response_headers,因为Selenium / ChromeDriver不支持它。但您可以使用File.basename()检查下载文件的文件名。

class Spinach::Features::FileDownload < Spinach::FeatureSteps
  include SharedAuthentication

  step 'I click on the download button' do
    click_link "Download"
  end

  step 'I should get zipped files' do
    File.basename(DownloadHelper.download_path).should == 'file.zip'
    Zip::ZipFile.open(DownloadHelper.download_path) do |zipfile|
      zipfile.find_entry('myfile.txt').should_not be_nil
      zipfile.find_entry('myphoto.jpg').should_not be_nil
    end
  end

end

答案 1 :(得分:15)

我必须在我的rails应用程序中做类似的事情。我的解决方案是使用Javascript对URL进行XMLHttpRequest,下载文件,将文件内容返回给Capybara,并使用ruby将文件保存在磁盘上的某个位置。然后在另一步中,我检查下载的CSV文件的内容。

以下是下载文件的步骤定义:

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

将Javascript代码中的网址更改为CSV的位置。

最后,这是验证CSV文件内容的步骤定义:

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
祝你好运。希望这会有所帮助。

答案 2 :(得分:4)

Poltergeist目前无法做到这一点。

我认为你最好为这个没有使用Capybara的CSV编写测试。 (例如,使用内置的Rails集成测试内容并将响应解析为CSV。)

答案 3 :(得分:2)

有一张支持在PhantomJS / Poltergeist中下载文件的票证,并且有一两个叉子声称他们以某种方式使其工作。见https://github.com/ariya/phantomjs/issues/10052