简体   繁体   English

如何测试带有x次参数的方法?

[英]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. 我创建了一个SourceReader类,该类可以解析文件,并根据文件中识别出的标记的数量产生多次。 For example if I parse file1.txt , it will yield with value one once only. 例如,如果我解析file1.txt ,它将只产生一次值为one Another example is when I parse file2.txt , it will yield twice, first with the value one , and then with the value two . 另一个示例是当我解析file2.txt ,它将产生两次,首先是值one ,然后是值two

How do I test this properly using rspec? 如何使用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感到困惑 expect { |b| object.action(&b) }.to yield_with_args found in the documentation 在文档中找到expect { |b| object.action(&b) }.to yield_with_args

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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