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
I think you need to use and_yield
instead of and_return
here.
Check rspec-mocks's README: https://github.com/rspec/rspec-mocks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With