Skip to content

Instantly share code, notes, and snippets.

@danajp
Created April 17, 2015 20:28
Show Gist options
  • Save danajp/5749b2ce3235aa95881b to your computer and use it in GitHub Desktop.
Save danajp/5749b2ce3235aa95881b to your computer and use it in GitHub Desktop.
Using RSpec Mocks' and_yield
class CSVOddUpcaser
# Pretty contrived, but whatever.
#
# Reads rows from a CSV object, upcases the data in the odd numbered
# rows and writes rows to a new CSV object.
def initialize(csv)
@csv = csv
end
def write(new_csv)
@csv.each_with_index do |row, i|
if i % 2 == 0
new_csv << row.map(&:upcase)
else
new_csv << row
end
end
end
end
describe CSVOddUpcaser do
# We stub a CSV instance because:
#
# 1. We'd like to define our test data as ruby data structures
# instead of csv strings
#
# 2. We don't want to couple our test to CSV. Any class that has
# #each_with_index and #<< can be used with CSVOddUpcaser.
let(:source_csv) { double }
let(:dest_csv) { double }
before do
allow(source_csv).to receive(:each_with_index).
and_yield(['first', 'row', 'data'], 0).
and_yield(['second', 'row', 'data'], 1).
and_yield(['third', 'row', 'data'], 2).
and_yield(['fourth', 'row', 'data'], 3)
end
describe '#write' do
it 'should upcase only the odd rows' do
expect(dest_csv).to receive(:<<).with(['FIRST', 'ROW', 'DATA']).ordered
expect(dest_csv).to receive(:<<).with(['second', 'row', 'data']).ordered
expect(dest_csv).to receive(:<<).with(['THIRD', 'ROW', 'DATA']).ordered
expect(dest_csv).to receive(:<<).with(['fourth', 'row', 'data']).ordered
upcaser = CSVOddUpcaser.new(source_csv)
upcaser.write(dest_csv)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment