【问题标题】:Rspec: how to test for yield selfRspec:如何测试产量自我
【发布时间】:2013-11-15 10:48:11
【问题描述】:

我正在使用 rspec 3.0.0.beta1。我必须测试一个产生self的方法:

class Test
  def initialize
    yield self if block_given?
  end
end

这是一个成功的测试:

describe Test do
  context 'giving a block with one argument' do
    it 'yields self'
      expect { |b| described_class.new &b }.to yield_with_args described_class
    end
  end
end

但它只测试对象类,不测试self的身份。

这是我写的最接近(失败)的测试:

describe Test do
  context 'giving a block with one argument' do
    it 'yields itself'
      instance = nil
      expect { |b|
        instance = described_class.new &b
      }.to yield_with_args instance
    end
  end
end

确实失败了,因为在评估最后一个实例出现时它是nil,因此它与块评估中的实例不匹配。

【问题讨论】:

    标签: ruby unit-testing testing rspec


    【解决方案1】:

    yield 匹配器不能直接用于您的情况。最简单的做法是稍后使用不同的匹配器对您的第二个代码进行变体。

    describe Test do
      context 'giving a block with one argument' do
        it 'yields itself'
          yielded_instance = nil
          new_instance = described_class.new { |i| yielded_instance = i }
          expect(yielded_instance).to be new_instance
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-23
      • 2013-02-24
      • 2012-12-13
      • 2019-03-09
      • 1970-01-01
      • 2013-07-13
      • 2022-07-06
      • 1970-01-01
      相关资源
      最近更新 更多