我正在尝试编写rails测试(使用Capybara& Poltergeist)来测试.zip文件下载功能。
我有从XHR请求返回的.zip文件的二进制数据,我希望将这些数据写入本地的.zip文件并从那里进行进一步的测试。
以下方法模拟按钮上的单击,当在应用程序中时,该按钮返回已选择的所有文件的zip文件:
# Perform XHR
def download_file(link)
page.execute_script("window.downloadFile = function(){ var url = window.location.protocol + '//' + window.location.host + '#{link}'; return getFile(url); }")
page.execute_script("window.getFile = function(url){ var xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.responseType = 'blob'; xhr.send(); return xhr.response; }")
begin
file = page.evaluate_script('downloadFile()')
rescue
raise "Error during XHR. Is url valid?"
end
file
end
我正在尝试将回复写入文件:
file = download_file(url)
file_path = "#{Rails.root}/tmp/files/download.zip"
File.open(file_path, 'wb'){ |f| f.write file }
尝试使用unzip tmp/files/download.zip
解压缩生成的文件时,我收到了以下回复:
Archive: tmp/files/download.zip
caution: zipfile comment truncated
error [tmp/files/download.zip]: missing 3182550208 bytes in zipfile
(attempting to process anyway)
error [tmp/files/download.zip]: start of central directory not found;
zipfile corrupt.
(please check that you have transferred or created the zipfile in the
appropriate BINARY mode and that you have compiled UnZip properly)
我尝试将MIME类型覆盖到text/plain
,application/zip
等,但无济于事。
有什么建议吗?
答案 0 :(得分:0)
我扩展了Tempfile类以包含写二进制函数
class Tempfile
def openBinary
@tmpfile.close if @tmpfile
@tmpfile = File.open(@tmpname, 'wb')
@data[1] = @tmpfile
__setobj__(@tmpfile)
end
end
这使我的系统可以解析zip文件,然后阅读使用Zip :: ZipFile类。