ruby 如何测试一个方法的收益率与参数x次?

fcy6dtqo  于 2023-03-22  发布在  Ruby
关注(0)|答案(2)|浏览(116)

我创建了一个类SourceReader,它解析一个文件,并根据文件中识别的标记的数量产生多次。例如,如果我解析file1.txt,它将只产生一次值one。另一个例子是,当我解析file2.txt时,它将产生两次,第一次是值one,然后是值two
如何使用rspec正确地测试它?以下是我到目前为止所做的:

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

我对如何实现文档中的expect { |b| object.action(&b) }.to yield_with_args感到困惑

hc8w905p

hc8w905p1#

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

cwxwcias2#

使用yield_successive_args

# ... setting up test subject `sut` ...

expect { |b| sut.each_card(&b) }.to yield_successive_args('one', 'two')

相关问题