使用 Capybara 和 Cucumber 测试文件下载

Test file download with Capybara and Cucumber

我正在尝试使用 Capybara 和 Cucumber 测试下载。

测试步骤如下:

When(/^I export to CSV$/) do
  export_button = find("div.results-table input[type=\"submit\"]")

  export_button.click
end

Then(/^I should be prompted to download the CSV$/) do
  Capybara.current_driver = :webkit #switch driver so we can see the response_headers
  page.response_headers['Content-Disposition'].should include("filename=\"transactions\"")
end

我不得不在测试过程中添加 capybara webkit 驱动程序以便我可以使用 response_headers,但是 response_headers 似乎 return 是一个空对象。之前我使用的是默认驱动程序,因为我需要单击按钮,但我想知道是否像这样切换驱动程序是我在 response_header?

中没有得到任何东西的原因

我在最近的项目中做了如下图

Given Download folder for export is empty
And   Joe clicks "Download Csv" button
Then  The contents of the downloaded csv should be:
|TEAM_ID | TEAM_EXTERNAL_ID | TYPE | REG_OPTION      | TEAM_REG_BRACKET | RACE_NAME  | WAVE      | BIB | BRACKET | STATUS    | TEAM_NAME | TEAM_TYPE | ATHLETE_COUNT | MIN_MEMBERS  | MAX_MEMBERS | TEAM_MEMBERS |
|    8   |                  | TEAM | 10k Aggregate   | N/A              | 10k        | Universal | 208 | Overall | DNF       | Team 08   | Aggregate |0              |              |             |              |

这条黄瓜的水豚会像

Given(/^Download folder for export is empty$/) do
  FileUtils.rm_rf('/home/vagrant/Downloads/')
end

And(/^(\S*) clicks "([^"]*)" button$/) do |user, arg|
  button = find_button(arg)
  button.click
end

And /^The contents of the downloaded csv should be:$/ do |table|
  for i in 0..5
      if(Dir.glob('/home/vagrant/Downloads/*.csv'))
        break;
      end
      sleep(1); // if not found wait one second before continue looping
  end

  if(Dir.glob('/home/vagrant/Downloads/*.csv'))
    Dir['/home/vagrant/Downloads/*'].each do |file_name|
      arr = CSV.read(file_name, :col_sep => "\t", :row_sep => "\r\n", encoding: "UTF-16:UTF-8")
      table.raw[0...table.raw.length].each_with_index do |row, row_index|
        row.each_with_index do |value, index|
          if arr[row_index][index] == nil
            arr[row_index][index] = ""
          end
          if index == 1
          else
            puts "#{index}" + 'Value in table = ' + "#{value} + 'Value in file' + #{arr[row_index][index]}"
            value.should eq arr[row_index][index]
          end
        end
      end
    end
  else
    puts "/home/vagrant/Downloads/*.csv file not found!"
  end
end

希望这能解决您下载 CSV 并验证其内容的问题:)