rspec-mocks: Custom failure messages for message expectations

103 views
Skip to first unread message

Jimmy

unread,
Feb 8, 2014, 4:06:55 AM2/8/14
to rs...@googlegroups.com
Hello,

I am wondering if there is a way to use a custom failure message for message expectations with rspec-mocks. I'm writing some helper methods that use message expectations under the hood. Unlike custom matchers from rspec-expectations, message expectations always give a failure message like this:

    Failure/Error: Unable to find matching line from backtrace
      Exactly one instance should have received the following message(s) but didn't: foo

I would like to be able to output an error message that speaks in the domain of my program. As an example, I'd like to use this text:

    Failure/Error: Message failed to trigger route
      Expected message "bar" to route to :foo, but didn't.

Is something like this possible? Thanks!

Jimmy

Myron Marston

unread,
Feb 8, 2014, 1:38:25 PM2/8/14
to rs...@googlegroups.com
There are two ways you could achieve this:
  •  Rather than using a normal message expectation, use a block implementation that keeps track of whether or not the message expectation has been satisifed, and raises an appropriate error if not.
called = false
allow(obj).to receive(:foo) { called = true }

# do stuff

expect(called).to eq(true), "Expected message "bar" to route to :foo, but didn't."
  • Write a matcher that works similarly to the `have_received` matcher.
allow(obj).to receive(:bar)

# do stuff

expect(obj).to have_routed(:bar).to(:foo)

Within your `have_routed` matcher, you can have it delegate to `have_received` internally, since you can use matchers from within custom matchers.

HTH,
Myron
Reply all
Reply to author
Forward
0 new messages