【问题标题】:rspec test result from csv.read mocking file来自 csv.read 模拟文件的 rspec 测试结果
【发布时间】:2011-03-07 11:02:19
【问题描述】:

我正在使用 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 方法尝试从文件中读取时,它会返回我的数据变量。然后我可以测试它是否等于我的结果变量。

【问题讨论】:

  • 你能发布失败规范的堆栈跟踪吗?你有没有inspect 模拟看看它是不是你认为的那样?

标签: ruby-on-rails file mocking rspec rspec2


【解决方案1】:

你可以存根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 对象(在这种情况下是一个文件)

【讨论】:

    【解决方案2】:

    存根 File.open 会破坏 pry。为避免这种情况,您可以存根CSV.read,它不如存根文件强大,但可以让您使用pry

        let(:data) do
          StringIO.new <<-CSV_DATA
            0;48;78;108;279;351;405;694;872;1696
            1.03;9.28;13.4;18.56;29.9;30.93;42.27;77.32;85.57;100.0
            0.0;2.94;8.82;11.76;44.12;97.06;100.0;100.0;100.0;100.0
          CSV_DATA
        end
        let(:csv_config) { { headers: true, return_headers: true, converters: :numeric } }
        
        before { allow(CSV).to receive(:read).with(csv_path, csv_config) { CSV.parse(data, csv_config) } }     
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      • 2021-10-16
      相关资源
      最近更新 更多