First of all, let's create the project folder
mkdir fibYeah, you guessed right, we'll deal with yet another Fibonacci sequence implementation ;)
Now, move in fib folder and create a basic project structure
cd fibAs you guess src will contain source files and spec will contain the specs. Now let's go creating a Makefile in the project base path. Create an empty Makefile using your favourite text editor and copy/paste the code below:
mkdir src
mkdir spec
These are the up-level's rules with which we will interact. Names are self-explanatory however I'll describe the corresponding actions below:
- make clean
- Clean up project folder removing intermediate and backup files
- make test
- Run the specs
- make format
- Format the source files using gofmt
- make package
- Build the package
Note that we have to set the PACKAGE variable with the name of the package (fib in this case). Also, note that the testpackage rule in the Makefile above will create a package named test$(PACKAGE).a. So, in our case, we will get src/testfib.a. We will import this package in our test code to actually run the specs.
At this point, the basic project structure and makefiles are done. Now, we can populate src/ folder with an empty source file (with just the basic package clause within):
cd srcNow, following BDD convention (test-first approach), let's write our test. Enter in spec/ folder and create spec/fib_spec.go with the code below:
echo "package fib" > fib.go
The spec above tell us how we expect the system behaves before actually implement it. In particular, we setup two seed values N0 and N1 and then we query fib about the next value in the sequence using fib.Next() method. For the first five calls we expect the sequence: 1, 1, 2, 3, 5.
If we try to run the specs at this point we get an error of course (we haven't an implementation yet):
$ makeOpen the text editor and paste in src/fib.go the code below:
...
fib_spec.go:9: undefined: testfib.Fib
...
If you're new to Go, take your time reading the code. Also consider that I'm still learning this language from the ground up so this could not be the best idiomatic implementation (waiting for suggestions in this case). BTW, for the purpose of this post, our code behave as we expect. In fact, running the specs
$ make testthey all pass.
.
Passing: 1 Failing: 0 Pending: 0 Errors: 0
Well, that's all for now! You can browse the source files used in this post on github.