How is 'provided' implemented in a fact in Midje?

873 views Asked by At

I was reading Clojure in Action chapter 8 about TDD and experimented with the stubbing macro. It uses the dynamic binding mechanism to stub functions. Alas, in Clojure 1.3 it is not possible to use the binding mechanism for non-dynamic vars, so the stubbing macro doesn't work in most cases, unless you explicitly declare the var which points to a function dynamic. Then I wondered how stubbing is done in Midje and tried to find the source for 'provided', but I couldn't find it. So here it goes:

How is 'provided' implemented in a fact in Midje? Can someone explain this in detail?

1

There are 1 answers

0
Brian Marick On BEST ANSWER

Clojure 1.3 provides a with-redefs macro that works even with vars that haven't been declared dynamic:

user=> (def this-is-not-dynamic)
user=> (with-redefs [this-is-not-dynamic 900] this-is-not-dynamic)
900

For backward compatibility, Midje uses its own version, whose guts look like this:

(defn alter-one-root [[variable new-value]]
   (if (bound? variable) 
     (let [old-value (deref variable)]
       (alter-var-root variable (fn [current-value] new-value))
       [variable old-value])
     (do
       (.bindRoot variable new-value)
       [variable unbound-marker])))