我正在尝试测试一种使用 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.
使用 Mocha::Expectations#multiple_yields:
检查 "="">此线程 了解为什么必须在另一个数组中传递行。
Use Mocha::Expectations#multiple_yields:
Check this thread to see why you have to pass the rows inside another array.