ruby-on-rails – csv.read嘲笑文件的rspec测试结果

我正在使用红宝石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

我基本上想要模拟一个文件,所以当CSV方法试图从文件中读取它返回我的数据变量.那么我可以测试它是否等于我的结果变量.

解决方法

你可以存档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)

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...