vendredi 6 février 2015

Minitest: How to stub/mock the file result of Kernel.open on a URL

I have been trying to use Minitest to test my code (full repo) but am having trouble with one method which downloads a SHA1 hash from a .txt file on a website and returns the value.


Method:



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


You can see that I log what is occurring to the command line, create an object to hold my SHA1 value, open the url (e.g. http://ift.tt/1C5yaVu)


I then split the string so that I only have the SHA1 value.


The problem is that during a test, I want to stub the Kernel.open which uses OpenURI to open the URL. I would like to ensure that I'm not actually reaching out to download any file, but rather I'm just passing the block my own mock IO object testing just that it correctly splits stuff.


I attempted it like the block below but when @remote_sha1 = file.read occurs the file item is nil.



@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

Aucun commentaire:

Enregistrer un commentaire