ruby – 存根和__如何只能例外一次?
发布时间:2020-12-17 03:05:40 所属栏目:百科 来源:网络整理
导读:我知道有一种方法可以让一个存根返回多个不同的值,如下所示: subject.stub(:method_call.and_return(1,2,3) 但我希望这样的事情是可能的: subject.stub(:method_call).and_raise(Exception).oncesubject.stub(:method_call).and_return(1) 但是我没有找到
我知道有一种方法可以让一个存根返回多个不同的值,如下所示:
subject.stub(:method_call.and_return(1,2,3) 但我希望这样的事情是可能的: subject.stub(:method_call).and_raise(Exception).once subject.stub(:method_call).and_return(1) 但是我没有找到一种优雅的方法让stub只在第一次调用时引发异常.建议? 解决方法
我知道这样做的唯一方法是使用这样的计数器变量:
counter = 0 times = 2 TestModel.any_instance.stub(:some_method) do (counter += 1) <= times ? raise(Exception) : 1 end 这将输出如下: test = TestModel.new test.some_method => Exception test.some_method => Exception test.some_method => 1 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |