我正在使用 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 < ActiveRecord::Base
attr_accessor :import_file
def import(filename)
CSV.read(filename, :row_sep => "\r", :col_sep => "\t")
end
end
我基本上想模拟一个文件,以便当 CSV 方法尝试从文件中读取时,它会返回我的数据变量。然后我可以测试它是否等于我的结果变量。
最佳答案
你可以 stub 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 对象(在这种情况下是一个文件)
关于ruby-on-rails - 来自 csv.read 模拟文件的 rspec 测试结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5218864/