我正在使用 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
,因此它与 block 评估内的实例不匹配。
最佳答案
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
关于ruby - Rspec:如何测试自己的产量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19999271/