-
Notifications
You must be signed in to change notification settings - Fork 129
Facts
Midje's metaphor is that you state certain facts about a future version of your program, then write the code to make those facts true. You enable Midje with (:use midje.sweet)
.
Here's the simplest form of fact:
(fact (+ 1 1) => 2)
A single fact
can have multiple clauses:
(fact
(+ 1 0) => 1
(* 1 1) => 1)
(You can use facts
if you prefer.) To distinguish these clauses from the whole fact
expression, we'll call them assertions.
Facts can have documentation strings, though nothing is done with them yet.
(facts "about arithmetic"
(+ 1 0) => 1
(* 1 1) => 1)
The assertions don't have to be at the top level of the fact. They can be nested (though not within other assertions!). That's most useful if you want to wrap them in let
expressions:
(facts "about arithmetic"
(let [additive-identity 0] (+ 1 additive-identity) => 1)
(let [multiplicative-identity 1] (* 1 multiplicative-identity) => 1))
The previous fact expression contains detail that is more likely to hurt than help understanding. It's not important that 1 plus the identity is 1, it's that any number plus the identity is the original number. In logic, we'd use variables to talk about that ("for all x where x is an integer..."), but Midje has to work with specific constant values. To make such statements clearer, you can use Metaconstants.
The right-hand-side of an assertion can be a function:
(fact 1 => odd?)
The result of evaluating the left-hand-side is passed as the single argument to the right-hand-side function. The assertion "checks out" if the result of the function is anything other than false
or nil
. Midje comes with some predefined Checkers.
Often, one fact will depend on another. Here's a way of saying that:
(fact
(animal-set (animals)) => #{"cow" "horse"}
(provided
(animals) => ["cow" "horse"]))
The expressions within the provided
clause apply to the previous assertion. They're called prerequisites. Prerequisites let you program top-down, implementing animal-set
before worrying about the implementation of animals
.