gpt4 book ai didi

ruby - 如何测试 Stack 在 Ruby 和 rspec 中是否有元素?

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:32 25 4
gpt4 key购买 nike

我的 Stack 模块有以下规范:

describe Stack do
let(:stackable_obj) { (Class.new { include Stack }).new }

describe '#stack' do
context 'when it has no elements' do
it 'is an empty array' do
expect(stackable_obj.stack).to eq([])
end
end
end
..
end

而且我看不出如何测试堆栈在不为空时返回元素。我的模块看起来像这样:

module Stack
def stack
@stack ||= []
end
end

我会模拟堆栈方法吗?我这样做了:

context 'when it has elements' do
it 'gives an array with the elements' do
allow(stackable_obj).to receive(:stack).and_return([1,2,3])
expect(stackable_obj.stack).to eq([1,2,3])
end
end

但不知何故,这似乎是一个无用的测试,因为我实际上是在 mock 我正在测试的方法。

最佳答案

在我看来,对您的it 'gives an array with the elements' 测试用例的 stub 级别太高了。你想确保调用 stackable_obj.stack 返回包含在 stackable_obj@stack 实例变量中的值,所以@stack 的值是我认为你想要 stub 的值:

context 'when it has elements' do
it 'gives an array with the elements' do
stackable_obj.instance_variable_set(:@stack, [1,2,3])
expect(stackable_obj.stack).to eq([1,2,3])
end
end

关于ruby - 如何测试 Stack 在 Ruby 和 rspec 中是否有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25735747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com