如何模拟像“each”这样的方法?

发布于 12-20 02:39 字数 956 浏览 8 评论 0 原文

我正在尝试测试一种使用 CSV.foreach 读取 csv 文件并对其进行一些处理的方法。它看起来像这样:

require 'csv'

class Csv_processor
  def self.process_csv(file)
    begin
      CSV.foreach(file) do { |row|
        # do some processing on the row
      end
    rescue CSV::MalformedCSVError
      return -1
    end
  end
end

CSV.foreach 将文件路径作为输入,读取文件并解析逗号分隔的值,为文件中的每一行返回一个数组。每个数组依次传递给代码块进行处理。

我想使用 Mocha 来存根 foreach 方法,这样我就可以在测试中控制 process_csv 方法的输入,而无需任何文件 I/O mumbo-jumbo。

所以测试会是这样的,

test "rejects input with syntax errors" do
  test_input = ['"sytax error" 1, 2, 3', '4, 5, 6', '7, 8, 9']
  CSV.expects(:foreach).returns( ??? what goes here ??? )
  status = Csv_processor.process_csv("dummy")
  assert_equal -1, status, "Status does not indicate error: #{status}"
end

我需要一种方法将我的 test_input 数组转换为 Mocha 可以使用的东西。我想我必须使用某种 proc 或 lambda,但我发现 proc、块和 lambda 的世界有点令人费解。

I'm trying to test a method that uses CSV.foreach to read in a csv file and does some processing on it. It looks something like this:

require 'csv'

class Csv_processor
  def self.process_csv(file)
    begin
      CSV.foreach(file) do { |row|
        # do some processing on the row
      end
    rescue CSV::MalformedCSVError
      return -1
    end
  end
end

CSV.foreach takes a file path as input, reads the file and parses the comma separated values, returning an array for each row in the file. Each array is passed in turn to the code block for processing.

I'd like to use Mocha to stub the foreach method so I can control the input to the process_csv method from my test without any file I/O mumbo-jumbo.

So the test would be something like this

test "rejects input with syntax errors" do
  test_input = ['"sytax error" 1, 2, 3', '4, 5, 6', '7, 8, 9']
  CSV.expects(:foreach).returns( ??? what goes here ??? )
  status = Csv_processor.process_csv("dummy")
  assert_equal -1, status, "Status does not indicate error: #{status}"
end

I need a way to turn my test_input array into something Mocha can work with. I think I have to use some sort of proc or lambda, but I find the world of procs, blocks and lambdas a bit of a mind-bender.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

薔薇婲 2024-12-27 02:39:25

使用 Mocha::Expectations#multiple_yields

CSV.expects(:foreach).multiple_yields([row_array1], [row_array2], ...)

检查 "="">此线程 了解为什么必须在另一个数组中传递行。

Use Mocha::Expectations#multiple_yields:

CSV.expects(:foreach).multiple_yields([row_array1], [row_array2], ...)

Check this thread to see why you have to pass the rows inside another array.

陌路黄昏 2024-12-27 02:39:25

使用 Proc 对象作为返回值:

Proc.new{ rand(100) }

use a Proc object as return value:

Proc.new{ rand(100) }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文