我正在寫一個測試我的課具有下面的構造之一:如何測試讀取文件?
def initialize(filepath)
@transactions = []
File.open(filepath).each do |line|
next if $. == 1
elements = line.split(/\t/).map { |e| e.strip }
transaction = Transaction.new(elements[0], Integer(1))
@transactions << transaction
end
end
我想用一個假的文件,而不是一個固定裝置來測試這一點。所以我寫了下面的規格:
it "should read a file and create transactions" do
filepath = "path/to/file"
mock_file = double(File)
expect(File).to receive(:open).with(filepath).and_return(mock_file)
expect(mock_file).to receive(:each).with(no_args()).and_yield("phrase\tvalue\n").and_yield("yo\t2\n")
filereader = FileReader.new(filepath)
filereader.transactions.should_not be_nil
end
不幸失敗,因爲我依靠$.
等於1和增量在每一行出於某種原因,在測試過程中不會發生。我怎樣才能確保它呢?
順便說一句,'open'和'each'鏈接與將'block'傳遞給'open'不同 - 你的示例中的文件對象將不會自動關閉。 – Stefan 2014-09-01 14:38:25