lulalala
lulalala

Reputation: 17991

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?

Upvotes: 18

Views: 15519

Answers (2)

cbliard
cbliard

Reputation: 7262

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

Upvotes: 31

Lucas Moulin
Lucas Moulin

Reputation: 2550

You can use Receive Counts:

expect(Logger).to receive(:log).with('foo').at_least(:once)

Upvotes: 13

Related Questions