【问题标题】:How to test a method that yields with arguments x times?如何测试产生x次参数的方法?
【发布时间】:2016-07-07 20:10:48
【问题描述】:

我创建了一个类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 感到困惑

【问题讨论】:

    标签: ruby rspec rspec3


    【解决方案1】:
    arr = []
    sut.each_card do |arg|
      arr << arg
    end
    expect(arr).to eq ['one', 'two']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2015-05-12
      • 2023-03-25
      相关资源
      最近更新 更多