简体   繁体   中英

How to test a method that yields with arguments x times?

I created a class SourceReader that parses a file and would yield as many times depending on the number of recognized tokens inside the file. For example if I parse file1.txt , it will yield with value one once only. Another example is when I parse file2.txt , it will yield twice, first with the value one , and then with the value two .

How do I test this properly using rspec? Here is what I have so far:

require './spec/spec_helper'

describe SourceReader do
  describe '#each_card' do

    context "given file with one card" do
      input_filename = './spec/data/file1_spec.txt'
      it 'yields once, with arguments "one"' do
        File.open(input_filename, 'r') do |file|
          sut = SourceReader.new(file)
          expect(sut.each_card).to yield_with_args('one')
        end
      end
    end

    context "given file with two cards" do
      input_filename = './spec/data/file2_spec.txt'
      it 'yields twice, with arguments "one", then "two"' do
        # some codes
      end
    end

  end
end

I am confused on how to implement the expect { |b| object.action(&b) }.to yield_with_args expect { |b| object.action(&b) }.to yield_with_args found in the documentation

arr = []
sut.each_card do |arg|
  arr << arg
end
expect(arr).to eq ['one', 'two']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM