RSpec is_anticipated helper

This is about a little helper method called is_anticipated which complements is_expected — a trial to make RSpec even nicer.

Photo by Jonathan Borba on Unsplash

RSpec is a testing framework for Ruby. It has a long history and it’s incredibly powerful. For tests which have a lot of context switches you may use the one-liner syntax. So you may write concise tests like these:

This may need a bit of practice to get used to, mainly because you may not immediately see the “act”-part of the test — it’s nested in the subject.

The problem

Now there’s a problem with the one-liner syntax, as stated in the docs:

The one-liner syntax only works with non-block expectations

This means you could not write a test like this (using db-query-matchers gem):

It would raise an error like this:

The solution

I often introduce my little helper method is_anticipated into projects. The very simple setup looks like this:

With that in place the following test works like a charm:

Why is_anticipated ?

Because “anticipate” means to expect something and take action in expectation while “expect” means regard as likely to happen and does not require any action.




I engineer software and craft beer, or the other way around. Find my old blog here:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store