加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:11:23 所属栏目:百科 来源:网络整理
导读:我正在使用红宝石1.9,我正在尝试做BDD.我的第一个测试’应该读取在csv的作品,但第二个我需要一个文件对象被嘲笑没有. 这是我的型号规格: require 'spec_helper'describe Person do describe "Importing data" do let(:person) { Person.new } let(:data) {
我正在使用红宝石1.9,我正在尝试做BDD.我的第一个测试’应该读取在csv的作品,但第二个我需要一个文件对象被嘲笑没有.

这是我的型号规格:

require 'spec_helper'

describe Person do
  describe "Importing data" do
    let(:person) { Person.new }

    let(:data) { "titletsurnametfirstnametrtitle2tsurname2tfirstname2tr"}
    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) { "titletsurnametfirstnamertitle2tsurname2tfirstname2r" }
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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读