来自csv.read模拟文件的rspec测试结果 [英] rspec test result from csv.read mocking file

查看:91
本文介绍了来自csv.read模拟文件的rspec测试结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ruby 1.9,并且正在尝试BDD.我的第一个测试应该在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.

这是我的型号规格:

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

我基本上想模拟一个文件,以便当CSV方法尝试从文件中读取文件时,它将返回我的数据变量.然后,我可以测试它是否等于我的结果变量.

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.

推荐答案

您可以存根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对象(在这种情况下为File)

StringIO essentially wraps a string and makes it behave like an IO object (a File in this case)

这篇关于来自csv.read模拟文件的rspec测试结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆