Ruby用StringIO模拟文件 [英] Ruby Mock a file with StringIO

查看:136
本文介绍了Ruby用StringIO模拟文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图借助Ruby中的StringIO模拟文件读取. 以下是我的测试,其次是我在主类中的方法.

I am trying to mock file read with the help of StringIO in Ruby. The following is my test and next to that is my method in the main class.

def test_get_symbols_from_StringIO_file
    s = StringIO.new("YHOO,141414")
    assert_equal(["YHOO,141414"], s.readlines)
end

def get_symbols_from_file (file_name)
  IO.readlines(file_name, ',')
end

我想知道这是否是我们模拟读取文件的方式,我也想知道类中是否还有其他方法可以模拟该方法,而不是与内容进行断言.

I want to know if this is the way we mock the file read and also I would like to know if there is some other method to mock the method in the class rather than doing assert equal with contents.

推荐答案

在测试中永远不会调用您的方法get_symbols_from_file.您只是在测试StringIO#readlines是否有效,即:

Your method get_symbols_from_file is never called in the test. You're just testing that StringIO#readlines works, i.e.:

StringIO.new("YHOO,141414").readlines == ["YHOO,141414"] #=> true

如果要使用StringIO实例作为文件的占位符,则必须更改方法以采用

If you want to use a StringIO instance as a placeholder for your file, you have to change your method to take a File instance rather than a file name:

def get_symbols_from_file(file)
  file.readlines(',')
end

FileStringIO实例均对readlines做出响应,因此上述实现可以同时处理这两个问题:

Both, File and StringIO instances respond to readlines, so the above implementation can handle both:

def test_get_symbols_from_file
  s = StringIO.new("YHOO,141414")
  assert_equal(["YHOO,141414"], get_symbols_from_file(s))
end

但是该测试失败:readlines包含行分隔符,因此它将返回包含两个元素"YHOO,"(请注意逗号)和"141414"的数组.您期望包含一个元素"YHOO,141414"的数组.

This test however fails: readlines includes the line separator, so it returns an array with two elements "YHOO," (note the comma) and "141414". You are expecting an array with one element "YHOO,141414".

也许您正在寻找这样的东西:

Maybe you're looking for something like this:

def test_get_symbols_from_file
  s = StringIO.new("YHOO,141414")
  assert_equal(["YHOO", "141414"], get_symbols_from_file(s))
end

def get_symbols_from_file(file)
  file.read.split(',')
end

如果您真的想使用IO::readlines,则可以创建 :

If you really want to use IO::readlines you could create a Tempfile:

require 'tempfile'

def test_get_symbols_from_file
  Tempfile.open("foo") { |f|
    f.write "YHOO,141414"
    f.close
    assert_equal(["YHOO", "141414"], get_symbols_from_file(f.path))
  }
end

这篇关于Ruby用StringIO模拟文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆