Getting Started with a Kata in Clojure Using Speclj
As I’m learning Clojure I’m going to be working on the katas that I also did in Ruby. These exercises helped me immensely with getting comfortable with a language: the syntax, finding new methods and new ways to do things, and also the red-green-factor cycle of a new testing framework. I’m starting out with the Prime Factors kata in Clojure and here’s a quick overview of setting up in Speclj for anyone else that wants to give it a whirl.
The Clojure Koans, which are currently maintained by Colin, use a specifically built koan-engine and Clojure syntax to make the assertions that help move you along. For example, the following code will simply return false
(= 2 4)
Speclj is a testing framework for Clojure that was developed by Micah, and just by requiring it in your project and spec files it provides you with a “should” syntax (among others) that should feel very familiar to anyone who has used RSpec. The same assertion as the one above in Speclj would look like this:
(should= 2 4)
In order to get up and running with the kata I set up a directory structure like this inside a folder named “primefactors_kata”:
Then inside of your project.clj file you’ll need to set up the project. This says what your project is, where things are, and lists the dependencies that the project needs.
(defproject prime-factors-kata "0.1"
:description "Kata in Clojure"
:dependencies [[org.clojure/clojure "1.4.0"]
[speclj "2.2.0"]]
:plugins [[speclj "2.2.0"]]
:test-paths ["spec/"]
:java-source-path "src/")
Then you’ll start with your primes_spec.clj file, which looks similar to a RSpec file, except that you need to say what namespace you are in, followed by what the test needs to “use”, a lá require
in Ruby
(ns primes-spec
(:use
[speclj.core]
[primes]))
(describe "Prime Factors"
(it "should factor 2"
(should= (primes-of 2) [2]))))
Now in order to run your tests you can use Leiningen (which you will need to install if you haven’t already), and the command in terminal is lein spec
to run all the tests once, or lein spec -a
to continuously run the tests. Once you run this it will add a folder called “target” to your directory, but you won’t need to do anything with it.
So, last but not least, over in the primes.clj file we just need to declare the namespace we’re working in and we can get down to making the tests pass. Note that the filename and the namespace matches the name from the “use” section of the primes_spec.clj file.
(ns primes)
(defn primes-of [x]
[2])
Obviously this is only enough code to make my first test pass and won’t return primes for any number larger than two, but hopefully this is enough to get you started. I’ll leave the rest of the solution up to you.