Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expect to receive with particular argument at least once

Tags:

rspec

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?

like image 979
lulalala Avatar asked Jun 26 '15 07:06

lulalala


2 Answers

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

like image 115
cbliard Avatar answered Oct 31 '22 11:10

cbliard


You can use Receive Counts:

expect(Logger).to receive(:log).with('foo').at_least(:once)
like image 20
Lucas Moulin Avatar answered Oct 31 '22 10:10

Lucas Moulin