@H_301_1@我正在使用红宝石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 < ActiveRecord::Base attr_accessor :import_file def import(filename) CSV.read(filename,:col_sep => "\t") end end
解决方法
你可以存档File.open:
let(:data) { "title\tsurname\tfirstname\rtitle2\tsurname2\tfirstname2\r" } let(:result) {[["title","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)