简体   繁体   中英

how to check a method is called with rspec

I want to check if a method is called with rspec.

I followed this instruction. https://relishapp.com/rspec/rspec-mocks/v/3-0/docs/message-expectations/receive-counts

I have a class Foo like this.

class Foo
  def run
    bar
  end
  def bar
  end
end

And this is spec file for it.

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

But it fails with this error.

  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)>'

How can I write rspec test for this run method?

You need to actually call the method under test, 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM