来自 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 < ActiveRecord::Base
attr_accessor :import_file
def import(filename)
CSV.read(filename, :row_sep => "\r", :col_sep => "\t")
end
end
我基本上想模拟一个文件,以便当 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.
Here is my model spec:
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
Here is the code so far:
class Person < ActiveRecord::Base
attr_accessor :import_file
def import(filename)
CSV.read(filename, :row_sep => "\r", :col_sep => "\t")
end
end
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以存根
File.open
:StringIO
本质上包装了一个字符串并使其表现得像一个IO对象(在本例中是一个File)You can stub
File.open
:StringIO
essentially wraps a string and makes it behave like an IO object (a File in this case)存根
File.open
会破坏pry
。为了避免这种情况,您可以存根CSV.read
,它不像存根文件那样强大,但可以让您使用pry
:Stubbing
File.open
breakspry
. To avoid this you can stubCSV.read
, which isn't as robust as stubbing file, but will let you usepry
: