【问题标题】:rspec stub CSV Foreach with headers: true带有标头的 rspec 存根 CSV Foreach:true
【发布时间】:2014-03-26 07:11:54
【问题描述】:

我花了一整天的时间来了解如何使用标头对这个 CSV Foreach 进行存根:在 RSPEC 中为 true,然后在 ROW 和 INDEX 中使用 do 块。我尝试了几件事,似乎不起作用。

这是我的模特

class Test

  def self.import(file_path)
    CSV.foreach(file_path, headers: true) do |row, index|
     Here the rest of the code to create/insert record
    end
  end

end

然后在rspec上,我尝试了这几种方法:

describe "Class" do
  context "successfully insert" do
    let(:data) { "name,lastname\nHero,SuperHero}" }

    before do
      # CSV foreach Stub here
      CSV.stub(:foreach).with("file_path", headers: true).and_return(data)
    end

    it "inserts new record" do
      expect do
       Test.import("file_path")
      end.to change(Test, :count).by(1)
    end
  end
end

它不起作用,它只会返回 CSV.foreach(file_path, headers: true) 的数据,但不会进入“do block”。

关于这件事的任何帮助,

非常感谢

【问题讨论】:

  • 你说的是什么意思,但它不会进入'do block'
  • 你能告诉我,你到底在找什么吗?如您所见,它应该返回data。原因是你把方法存根了,所以它没有调用实际的方法,同样的原因do..end也不会被执行。

标签: ruby-on-rails rspec rspec-rails


【解决方案1】:

我认为您需要在这里使用and_yield 而不是and_return

查看 rspec-mocks 的 README:https://github.com/rspec/rspec-mocks

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-21
    • 2016-11-17
    • 2019-08-21
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    相关资源
    最近更新 更多