gpt4 book ai didi

rspec - 只模拟一次方法

转载 作者:行者123 更新时间:2023-12-04 01:59:27 24 4
gpt4 key购买 nike

在替换原来的模拟方法之前,有没有办法模拟一个方法一次并且每个期望只模拟一次?

我认为这样的事情会起作用(注意 once )

class Klass
def self.meth
'baz'
end
end

describe Klass do
subject{ described_class.meth }
before{ allow(described_class).to receive(:meth).once.and_return('foo') }
it{ is_expected.to eq 'foo' }
context 'throwing in a context just to test' do
it{ is_expected.to eq 'foo' }
it{ is_expected.to eq 'foo' }
it{ is_expected.to eq 'foo' }
it 'only mocks once' do
expect(subject).to eq 'foo'
expect(subject).to eq 'baz' # this is the key
end # pass
end
end

不幸的是,我收到此错误:
   (Klass (class)).meth(no args)
expected: 1 time with any arguments
received: 2 times

如果我说 expect(Klass).to receive(:meth).once,我会预料到会失败而不是更宽容 allow .

我想知道如何才能模拟一次并且每个期望只模拟一次。

最佳答案

这可能有点不直观,但您可以通过 specifying different return values for multiple calls 来做到这一点。的 Klass.meth .

在您的情况下,您可以将第一个电话 stub 到 Klass.meth'foo' ,然后每隔一次调用 Klass.meth与方法的原始实现。看起来像这样:
allow(described_class).to receive(:meth).and_return('foo', described_class.meth)
我们需要在您的测试中更改的下一件事是不使用 subject在最后的测试中,因为它记录了 Klass.meth 时返回的值第一次被调用(这就是为什么所有其他使用 subject 的测试仍然会通过的原因),因此在 it 'only mocks once' 中做出第二个期望测试失败。相反,我们可以直接在每个规范中调用该方法:

class Klass
def self.meth
'baz'
end
end

describe Klass do
subject { described_class.meth }

before do
allow(described_class).to \
receive(:meth).and_return('foo', described_class.meth)
end

it { is_expected.to eq 'foo' }

context 'throwing in a context just to test' do
it { is_expected.to eq 'foo' }
it { is_expected.to eq 'foo' }
it { is_expected.to eq 'foo' }

it 'only mocks once' do
expect(described_class.meth).to eq 'foo'
expect(described_class.meth).to eq 'baz'
end # pass
end
end

关于rspec - 只模拟一次方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32964642/

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