rspec

Expect to receive with particular argument at least once


I have a Logger class. I want to test that inside the function, the Logger will receive a log call with foo argument.

expect(Logger).to receive(:log).with("foo")
Bar.foo()

However during this some model callback will also call Logger.log("euu"), Logger.log("arr"), Logger.log("hmm") and many others. Rspec seems to fails because log was called with some other arguments first.

I am only concerned that log("foo") is called once. Is there a way to do this kind of testing?


Solution

  • The approach is to allow calls to log, do your stuff, and then check that log has been called with the expected arguments, like this:

    allow(Logger).to receive(:log)
    Bar.foo
    expect(Logger).to have_received(:log).with("foo")
    

    RSpec calls this pattern Spies