【问题标题】:how to check a method is called with rspec如何检查使用 rspec 调用的方法
【发布时间】:2014-05-22 13:31:17
【问题描述】:

我想检查一个方法是否被 rspec 调用。

我遵循了这个指示。 https://relishapp.com/rspec/rspec-mocks/v/3-0/docs/message-expectations/receive-counts

我有一个像这样的类 Foo。

class Foo
  def run
    bar
  end
  def bar
  end
end

这是它的规范文件。

require_relative 'foo'

describe Foo do
  let(:foo){ Foo.new }
  describe "#run" do
    it "should call bar" do
      expect(foo).to receive(:bar)
    end
  end
end

但它失败并出现此错误。

  1) Foo#run should call foo
     Failure/Error: expect(foo).to receive(:bar)
       (#<Foo:0x007f8f9a22bc40>).bar(any args)
           expected: 1 time with any arguments
           received: 0 times with any arguments
     # ./foo_spec.rb:7:in `block (3 levels) in <top (required)>'

如何为这个run 方法编写rspec 测试?

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    您需要实际调用被测方法run

    describe Foo do
      let(:foo){ Foo.new }
      describe "#run" do
        it "should call bar" do
          expect(foo).to receive(:bar)
          foo.run # Add this
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 2017-11-19
      • 2021-09-12
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多