加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何检查对rspec中构造函数调用的方法的调用?

发布时间:2020-12-17 04:01:13 所属栏目:百科 来源:网络整理
导读:如果我有一个构造函数调用另一个函数的类,我如何检查它被调用和正确的次数? class MyClass def initialize(count) count.times{self.do_something} end def do_something # whatever endend 我想说点什么 n = 4MyClass.new(n).should_receive(:do_something
如果我有一个构造函数调用另一个函数的类,我如何检查它被调用和正确的次数?

class MyClass
  def initialize(count)
    count.times{self.do_something}
  end

  def do_something
    # whatever
  end

end

我想说点什么

n = 4
MyClass.new(n).should_receive(:do_something).exactly(n).times
n = 2
MyClass.new(n).should_receive(:do_something).exactly(n).times

但是失败是因为在do_receive被附加到它之前调用了do_something(至少我认为这就是原因).

expected: 4 times with any arguments
received: 0 times with any arguments

或者从构造函数中调用这样的东西是错误的,我应该重构?

此外,这个问题与此非常相似:

rspec: How to stub an instance method called by constructor?

但是我希望在过去的5年里,答案比设置短线新呼叫的手动实现更好.

解决方法

执行此操作的新语法如下:

allow_any_instance_of(ExampleClass).to receive(:example_method).and_return("Example")
expect_any_instance_of(ExampleClass).to receive(:example_method).and_return("Example")

See the docs

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读