Can you get the Clojure macro to evaluate its arguments?

I am trying to define a helper function that wraps clojure.test/deftest . Here is my general idea:

 (defn test-wrapper [name & body] (deftest (symbol (clojure.string/replace name #"\W" "-")) body))) 

However, since the first deftest argument deftest not evaluated, it throws an exception because it is a form, not a symbol. Is there a way to get the form to evaluate first?

+4
source share
2 answers

A better approach is to make test-wrapper a macro. Macros don't evaluate their arguments unless you say them. You can manipulate the arguments and replace them in some generated code as follows:

 (use 'clojure.test) (defmacro test-wrapper [name & body] (let [test-name (symbol (clojure.string/replace name #"\W" "-"))] `(deftest ~test-name ~@body ))) (test-wrapper "foo bar" (is (= 1 1))) (run-tests) 
+3
source

There is no way to make a macro (which you do not write) evaluate its arguments.

The best way to make your test-wrapper do what you want is to turn it into a macro itself. He can then evaluate the call to symbol itself and then go on to deftest with the result of calling symbol as the first argument.

+4
source

All Articles