我一直在尝试使用Minitest来测试我的代码(full repo),但是在从.txt下载SHA1哈希的一种方法遇到问题文件在网站上并返回值。Minitest:如何在URL上残留/模拟Kernel.open的文件结果
方法:
def download_remote_sha1
@log.info('Downloading Elasticsearch SHA1.')
@remote_sha1 = ''
Kernel.open(@verify_url) do |file|
@remote_sha1 = file.read
end
@remote_sha1 = @remote_sha1.split(/\s\s/)[0]
@remote_sha1
end
你可以看到,我记录的内容发生在命令行,创建一个对象来保存我的SHA1值,打开网址(如https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.4.2.deb.sha1.txt)
我再拆该字符串,以便我只有SHA1值。
问题是,在测试过程中,我想对使用OpenURI打开URL的Kernel.open
进行存根。我想确保我没有真正下载任何文件,但是我只是通过阻止我自己的模拟IO对象来测试它是否正确地分割了一些东西。
我试过它像下面的块,但是当@remote_sha1 = file.read
发生时,文件项目是零。
@mock_file = Minitest::Mock.new
@mock_file.expect(:read, 'd377e39343e5cc277104beee349e1578dc50f7f8 elasticsearch-1.4.2.deb')
Kernel.stub :open, @mock_file do
@downloader = ElasticsearchUpdate::Downloader.new(hash, true)
@downloader.download_remote_sha1.must_equal 'd377e39343e5cc277104beee349e1578dc50f7f8'
end
嗨,你能请ACC埃普马特的答案,而不是我的?在我想清楚发生了什么之前,他发布了正确的答案。谢谢。 – 7stud 2015-02-07 06:05:28