Rspec:期望模块接收方法

ste*_*och 3 unit-testing rspec ruby-on-rails

我有一个非常简单的模块:

module Foo
  def self.quux
    begin
      # stuff here
    ensure
      Baz.print_stuff
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

然后我有一个失败的简单测试:

describe Foo
  describe '.quux' do
    it "should print stuff" do
      Foo.quux
      expect(Baz).to receive(:print_stuff)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

当我运行此命令时,我收到以下错误消息:

Failures:

1) Foo.quux should should print stuff
   Failure/Error: expect(Baz).to receive(:print_stuff)
     (Baz).print_stuff(any args)
         expected: 1 time with any arguments
         received: 0 times with any arguments
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我知道该print_stuff方法正在被调用。

ste*_*och 6

解决方案:

describe Foo
  describe '.quux' do
    it "should print stuff" do
      expect(Baz).to receive(:print_stuff)
      Foo.quux
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

将期望值放在对 Foo.quux 的方法调用之前。

哎哟!