本文介绍了来自 csv.read 模拟文件的 rspec 测试结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 ruby 1.9 并且我正在尝试进行 BDD.我的第一个测试应该在 csv 中读取"有效,但第二个我需要模拟文件对象的测试无效.
I'm using ruby 1.9 and I'm trying to do BDD. My first test 'should read in the csv' works, but the second where I require a file object to be mocked doesn't.
这是我的模型规格:
require 'spec_helper'
describe Person do
describe "Importing data" do
let(:person) { Person.new }
let(:data) { "title surname firstname
title2 surname2 firstname2
"}
let(:result) {[["title","surname","firstname"],["title2","surname2","firstname2"]] }
it "should read in the csv" do
CSV.should_receive(:read).
with("filename", :row_sep => "
", :col_sep => " ")
person.import("filename")
end
it "should have result" do
filename = mock(File, :exists? => true, :read => data)
person.import(filename).should eq(result)
end
end
end
这是目前的代码:
class Person < ActiveRecord::Base
attr_accessor :import_file
def import(filename)
CSV.read(filename, :row_sep => "
", :col_sep => " ")
end
end
我基本上想模拟一个文件,这样当 CSV 方法尝试从文件中读取时,它会返回我的数据变量.然后我可以测试它是否等于我的结果变量.
I basically want to mock a file so that when the CSV method tries to read from the file it returns my data variable. Then I can test if it equals my result variable.
推荐答案
您可以存根 File.open
:
let(:data) { "title surname firstname
title2 surname2 firstname2
" }
let(:result) {[["title","surname","firstname"],["title2","surname2","firstname2"]] }
it "should parse file contents and return a result" do
expect(File).to receive(:open).with("filename","rb") { StringIO.new(data) }
person.import("filename").should eq(result)
end
StringIO
本质上包装了一个字符串并使其表现得像一个 IO 对象(在本例中为 File)
StringIO
essentially wraps a string and makes it behave like an IO object (a File in this case)
这篇关于来自 csv.read 模拟文件的 rspec 测试结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!