Tom Crayford
Tom Crayford

Reputation: 527

Finding vars from dynamically created namespaces in clojure

The following test fails:

(ns clojure_refactoring.rename-fn-test
  (:use clojure.test))

(deftest test-fn-location
  (in-ns 'refactoring-test-fn-rename)
  (clojure.core/refer-clojure)
  (defn a [b] (inc b))
  (in-ns 'clojure_refactoring.rename-fn-test)
  (is (not= (find-var 'refactoring-test-fn-rename/a)
        nil))
  (remove-ns 'refactoring-test-fn-rename))

That is, find-var (of a var I've just created, in a namespace I've just create) returns nil. This behaviour doesn't happen at the repl, where typing out the steps of the test works just fine.

Am I doing something wrong, or is this just something that doesn't work in clojure right now?

Upvotes: 4

Views: 899

Answers (1)

Michał Marczyk
Michał Marczyk

Reputation: 84331

Updated to a version which really seems to do the intended thing, in contrast to my original answer...

This version seems to work:

(ns clojure-refactoring.rename-fn-test
  (:use clojure.test
        [clojure.contrib.with-ns :only [with-ns]]))

(deftest test-fn-location
  (create-ns 'refactoring-test-fn-rename)
  (with-ns 'refactoring-test-fn-rename
    (clojure.core/refer-clojure)
    (defn a [b] (inc b)))
  (is (not= (find-var 'refactoring-test-fn-rename/a)
        nil))
  (remove-ns 'refactoring-test-fn-rename))

Also, you really need to change all occurrences of _ in namespace names to -, and the other way around for filenames.

With these changes in place, the test runs fine for me. (I haven't even tried to run it Apparently it still works without making the _ / - changes, but really, you need to do it! That's the accepted convention and things are not guaranteed to work if you don't follow it.)

For some reason, the code from the question seems to have been creating the Var a in the namespace the test was being defined in, thus (find-var 'clojure-refactoring.rename-fn-test/a) was returning a Var, whereas the test failed. With the above, (find-var 'clojure-refactoring.rename-fn-test/a) returns nil, as expected.

Upvotes: 1

Related Questions