Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock CSV foreach method in Rspec

I have a method that uses CSV.foreach method. The data should look like that:

1,0,0,1

1,1,0,0

I want to write a test which expects an error if I the number of elements is not the same in each line.

Something like:

it "should raise an error if input file lines size differ" do
  expect { my_method(invalid_file_name) }.to raise_error
end

How do I mock CSV's foreach method to return invalid input?

like image 410
danevron Avatar asked Jan 13 '23 19:01

danevron


1 Answers

You can indeed stub CSV's foreach method, but you need to use the and_yield method and chaining to generate more than one line, to wit:

CSV.stub(:foreach).and_yield(<first_line>).and_yield(<second_line)
like image 105
Peter Alfvin Avatar answered Jan 17 '23 07:01

Peter Alfvin