HTTPS clone URL

SSH clone URL

I'm a fan of MiniTest::Spec. It strikes a nice balance between the simplicity of TestUnit and the readable syntax of RSpec. When I first switched from RSpec to MiniTest::Spec, one thing I was worried I would miss was the ability to add matchers. (A note in terminology: "matchers" in MiniTest::Spec refer to something completely different than "matchers" in RSpec. I won't get into it, but from now on, let's use the proper term: "expectations").

Understanding MiniTest::Expectations

Let's take a look in the code (I'm specifically referring to the gem, not the standard library that's built into Ruby 1.9):

That entire module is filled with almost nothing but one-line "definitions". They each give a very brief description and instructions to see the related assertion. One great thing about MiniTest::Spec is that it's built right on top of MiniTest::Unit, which is very simple and therefor very fast. infect_an_assertion simply calls the assertion and passes the arguments. For example, from the above definition:

Notice the order of 'foobar' and String in the assertion as opposed to the expectation. See how they're flipped? The convention for the order of arguments in an assertion is expected value goes first, then actual value. With expectations, it's the opposite:

assert_equal 'expected', 'actual' and 'actual'.must_equal 'expected'

Let's look at another example:

infect_an_assertion :assert_includes, :must_include, :reverse

assert_includes [1, 2, 3], 1 is the same as [1, 2, 3].must_include 1. But notice that the order of the arguments isn't flipped. That's why the :reverse argument above is needed.

Similarly, another example of when it's necessary not to flip the arguments is when there is only 1 argument. For example:

infect_an_assertion :assert_empty, :must_be_empty, :unary

The assertion is assert_empty [], and the expectation is [].must_be_empty. infect_an_assertion splats (*args) the arguments, so the lack of arguments to flip doesn't mess up anything. But we do need to flip, nevertheless. The :unary argument does this for us. It does exactly the same thing the :reverse argument does. In fact, anything other than nil or false will work, but it's good to be descriptive.

Writing our own custom assertion/expectation

Now that we understand how MiniTest::Expectations uses infect_an_assertion to define expectations, let's write our own custom assertions and corresponding expectations.

Notice that I was specific about what I used to call infect_an_assertion. infect_an_assertion is a method defined on Module, which means we can call it on just about anything. I was specific about String and Hash because I only want those expectations to be defined on instances of those classes. I defined must_round_to on Numeric because both Integer and Float (among others) respond to round.

The code above is completely executable. It works with Ruby built-in MiniTest too. Play around with it.