First Steps with Erlang (Update)

By Kevin, November 2nd, 2018

Shortly after publishing my last post about Erlang, I noticed a bug in the code which would not have happened if I wrote unit test(s) first. I did not do that simply because I just started learning, and didn’t want too many barriers up front to getting started (its hard to write tests when you are learning new syntax and methodology).

Yet when I saw the bug, I couldn’t let that slide, as here again is another reinforcement of having tests. So I opened the project back up, pretended I have no awareness of the bug, and went from there.

After some quick reading of the docs, I created an EUnit test file and started filling in what I should expect:


-module(color_test).
-author("kevinquillen").
-include_lib("eunit/include/eunit.hrl").

simple_test() ->
  ?assertEqual("purple", color:get("")),
  ?assertEqual("purple", color:get("vrefn")),
  ?assertEqual("green", color:get("GrEeN")),
  ?assertEqual("purple", color:get("PURPLE")),
  ?assertEqual("orange", color:get("OrAnge")),
  ?assertEqual("blue", color:get("BlUe")),
  ?assertEqual("yellow", color:get("yellow")),
  ?assertEqual("grey", color:get("grey")),
  ?assertEqual("red", color:get("red")),
  ?assertNotEqual("black", color:get("BLACK")),
  ?assertNotEqual("OrAnge", color:get("OrAnge")),
  ?assertNotEqual("orange", color:get("orange ")).

Upon running this test, it would have told me I forgot to include an approved color, orange:


> color_test:simple_test().
** exception error: {assertEqual,[{module,color_test},
                                  {line,10},
                                  {expression,"\"orange\""},
                                  {expected,"purple"},
                                  {value,"orange"}]}
     in function  color_test:'-simple_test/0-fun-4-'/0 (color_test.erl, line 10)
     in call from color_test:simple_test/0 (color_test.erl, line 10)

Whoops! A quick update to the module and re-running the test results in:


> color_test:simple_test().
ok

Lesson learned. Although I am not sure why my function has to be called simple_test else it won’t be recognized.. I am sure I will find out as I go along.

I added my code on GitHub for reference.

Tags