A thirty-one line test framework
This post is out of date
This post has been migrated from my old blog. It may have broken links, or missing content.
I’ve been reading “Metaprogramming Ruby” the last couple days, and realizing that a lot of what makes Rspec amazing is its usage of metaprogramming. I thought it would be interesting to try and write my own test framework.
Surprisingly, it only took a couple minutes to write something quite powerful. freeman
is the gem that I produced.
It’s very simple - it extends the Object
class to add methods for #is
and isnt
, and the Kernel
class for a test
method.
Each test creates a Struct
, which takes the name of the test and the do..end
block (the code itself), and evaluates it as true
or false
. This is what is a test is, after all!
Here’s the definition of should
in Rspec:
And the definition of RSpec::Expectations::PositiveExpectationHandler
:
The simplest version? It compares the “actual” with the provided block, checking for equality. Here’s the freeman
version:
Some of the things are extra: the puts
statement is just to have some sense of output - I considered taking it out and just returning true or false but that’s not super helpful when you’re writing a separate test file.
I love Rspec
. I wrote freeman
because I want to understand how Rspec
works in a more well-rounded route. In the meantime, I’ve begun integrating freeman
in some personal scripts that don’t require full testing frameworks, and I’m impressed with how fast it is.
A simple test with freeman.rb
required outside of the gem:
With the gem:
It’s surprising the amount of time using Bundler can add to the script. Either way, it’s quite quick!