Is there a way to have fixtures that are specific to a certain tests and not all in the given namespace?

543 Views Asked by At

just like midje lets us wrap facts in a with-state-changes form to specify what should run specifically before, around or after them or the content, how does one accomplish the same with clojure.test

1

There are 1 best solutions below

2
On

fixtures in clojure.test are functions that take a function as an argument, do some setup, call the function, then do some cleanup.

tests (as created with deftest) are functions that take no arguments and run the appropriate tests.

So to apply a fixture to a test you just wrap that test in the fixture

user> (require '[clojure.test :refer [deftest is testing]])
nil

a function to test:

user> (def add +)
#'user/add

a test for it:

user> (deftest foo (is (= (add 2 2) 5)))
#'user/foo

create a fixture that changes math so the test can pass:

user> (defn new-math-fixture [f]
        (println "setup new math")
        (with-redefs [add (constantly 5)]
          (f))
        (println "cleanup new math"))
#'user/new-math-fixture

without the fixture the test fails:

user> (foo)

FAIL in (foo) (form-init5509471465153166515.clj:574)
expected: (= (add 2 2) 5)
  actual: (not (= 4 5))
nil

and if we change math our test is fine:

user> (testing "new math"
        (new-math-fixture foo))
setup new math
cleanup new math
nil
user> (testing "new math"
        (deftest new-math-tests
          (new-math-fixture foo)))
#'user/new-math-tests
user> (new-math-tests)
setup new math
cleanup new math
nil