我有一个类,在一种情况下应该调用:my_method
,但在另一种情况下不能调用方法:my_method
。我想测试这两种情况。另外,我希望测试记录不应调用 :my_method
的情况。
Using any_instance
is generally discouraged ,所以我很乐意学习一种替代它的好方法。
此代码片段是我想要编写的测试类型的简化示例。
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
希望这对您有所帮助!
关于ruby-on-rails - 如果没有 any_instance,如何断言没有进行方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52889179/