来自csv.read模拟文件的rspec测试结果

我正在使用ruby 1.9而我正在尝试做BDD。 我的第一个测试“应该在csv中读取”,但是第二个我需要模拟文件对象的测试却没有。

这是我的型号规格:

require 'spec_helper' describe Person do describe "Importing data" do let(:person) { Person.new } let(:data) { "title\tsurname\tfirstname\t\rtitle2\tsurname2\tfirstname2\t\r"} let(:result) {[["title","surname","firstname"],["title2","surname2","firstname2"]] } it "should read in the csv" do CSV.should_receive(:read). with("filename", :row_sep => "\r", :col_sep => "\t") 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  "\r", :col_sep => "\t") end end 

我基本上想要模拟一个文件,以便当CSV方法尝试从文件中读取时它返回我的数据变量。 然后我可以测试它是否等于我的结果变量。

你可以存根File.open

 let(:data) { "title\tsurname\tfirstname\rtitle2\tsurname2\tfirstname2\r" } 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)