rspec存根CSV带有标头的Foreach:true

kil*_*lua 5 rspec ruby-on-rails rspec-rails

我花了一整天的时间来了解如何使用标题来存储此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
Run Code Online (Sandbox Code Playgroud)

然后在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
Run Code Online (Sandbox Code Playgroud)

它不起作用,它只返回CSV.foreach(file_path,headers:true)的数据,但它不会转到'do block'.

对此有任何帮助,

非常感谢你

Jua*_*tas 1

我认为你需要使用and_yield而不是and_return这里。

检查 rspec-mocks 的自述文件:https://github.com/rspec/rspec-mocks