Rspec:期望模块接收方法

时间:2015-07-02 17:30:26

标签: ruby-on-rails unit-testing rspec

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

module Foo
  def self.quux
    begin
      # stuff here
    ensure
      Baz.print_stuff
    end
  end
end

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

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

运行时出现以下错误消息:

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

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

1 个答案:

答案 0 :(得分:1)

解决方案:

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

将方法调用之前的期望放到Foo.quux。

卫生署!