问题描述
我有一个类,在一种情况下应该调用:my_method
,但在另一种情况下不能调用方法:my_method
.我想测试这两种情况.另外,我希望测试记录不应该调用 :my_method
的情况.
I have a class, that in one situation should call :my_method
, but in another situation must not call method :my_method
. I would like to test both cases. Also, I would like the test to document the cases when :my_method
should not be called.
使用any_instance
通常不鼓励,所以我很乐意学习一个很好的方法来替换它.
Using any_instance
is generally discouraged, so I would be happy to learn a nice way to replace it.
这个代码片段是我想要编写的测试类型的简化示例.
This code snippet is a reduced example on what I kind of test I would like to write.
class TestSubject
def call
call_me
end
def call_me; end
def never_mind; end
end
require 'rspec'
spec = RSpec.describe 'TestSubject' do
describe '#call' do
it 'calls #call_me' do
expect_any_instance_of(TestSubject).to receive(:call_me)
TestSubject.new.call
end
it 'does not call #never_mind' do
expect_any_instance_of(TestSubject).not_to receive(:never_mind)
TestSubject.new.call
end
end
end
spec.run # => true
它有效,但使用了 expect_any_instance_of
方法,不推荐使用.
It works, but uses expect_any_instance_of
method, which is not recommended.
如何更换?
推荐答案
我会做类似的事情
describe TestSubject do
describe '#call' do
it 'does not call #something' do
subject = TestSubject.new
allow(subject).to receive(:something)
subject.call
expect(subject).not_to have_received(:something)
end
end
end
希望这有帮助!
这篇关于如何在没有 any_instance 的情况下断言未进行方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!