Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rspec stub CSV Foreach with headers: true

I have spent the whole day to find out how to stub this CSV Foreach with headers: true in RSPEC and then with the do block for ROW and INDEX. I have tried couple of things, seems it does not work.

This is my model

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

Then on the rspec, I have tried these couple of ways:

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

And it does not work, it will just return the data for CSV.foreach(file_path, headers: true) but it wont go to the 'do block'.

Any help on this matters,

Thank you very much

like image 679
kilua Avatar asked Nov 11 '22 10:11

kilua


1 Answers

I think you need to use and_yield instead of and_return here.

Check rspec-mocks's README: https://github.com/rspec/rspec-mocks.

like image 111
Juanito Fatas Avatar answered Nov 15 '22 04:11

Juanito Fatas