我有一堂课,在一种情况下应该调用:my_method
,但在另一种情况下不得调用方法:my_method
。我想测试这两种情况。另外,我希望测试能够记录以下情况::my_method
不应该被调用。
Using any_instance一般不鼓励 https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/any-instance,所以我很乐意学习一种替代它的好方法。
此代码片段是我想要编写的测试类型的简化示例。
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
方法,不推荐。
如何更换?
我会做类似的事情
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
希望这有帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)