Posts Tagged ‘tdd’

An interview with Michał Ślaski about TDD and testing in Erlang

February 16, 2015 Leave a comment

Hello! After a very veeeeeeeeery long time I had the chance to write again in this blog and for me this is awesome: this year I promise myself to keep this blog up and running (or restart doing it using a supervisor 😛 ).

Getting back to serious stuff, today you may read my interview to Michał Ślaski from Erlang Solutions Kraków. Because of his experience as a developer and trainer I strongly recommend this interview not only to Erlang developers, but also to all the readers interested in TDD, testing and automation.

 Exploring TDD and testing in a functional world


Paolo – Hello Michał, thank you for being here with us! Would you like to introduce yourself to our readers?

Michał –  Hello, thanks for having me. My name is Michał Ślaski and I’m a senior architect at Erlang Solutions, branch manager of the Kraków office, founder of Lambda Academy and co-chair of the Lambda Days conference.

Paolo – Can you tell us how you started working with Erlang and how you discovered Test Driven Development?

Michał – In 2004 my friend and I came up with a proposal for our Master’s Degree project, which was a massively multiplayer on-line game. At the time we were working as C++/DirectX developers at one of the game studios in Kraków. We went to our supervisor, described the proposal, and he suggested we use Erlang on the server side. My friend implemented the front-end in Java3D and I implemented the back-end in Erlang + Mnesia. One year later I graduated and soon after got an interview at Erlang Solutions in London. I met with Francesco Cesarini and presented my Master’s Thesis about prototyping MMOGs with Erlang. It is a mystery to me why I got the job at Erlang Solutions, because the thesis was written in Polish…Francesco helped me publish a presentation at the Erlang User Conference in Stockholm and you can find it here:

Paolo – You give courses about Erlang and TDD. Can you please explain to our readers new to TDD what it is and why we should apply this practice when writing our Erlang code?

Michał – Let me quote our training material here as it answers your question well. Testing is as old as programming itself. It is useful to document behaviours and demonstrate that a program has the required properties. Testing was traditionally done after writing code. Test-Driven Development dictates that tests should be written before the code. Writing tests before the code is not used for testing, but for design. Tests represent the specification to be implemented. Testing before writing code asks the developer to think about interfaces and how to use the code. It ensures that the application is written for testability, and ensures that parts of the application are modular and reusable. Tests are a side effect of test-driven development.

Paolo – Many confuse TDD with the so-called “test first”, but TDD is not only about tests, is also about design. Do you think that in Erlang as well we can apply TDD to explore the system and to build software with a better design?

Michał – Yes, Erlang being a functional language is a good fit for TDD. When we design Erlang systems we need to think not only about unit testing, but also about integration testing, system testing and acceptance testing. If you can have test cases on different levels it helps ensure both the design and the implementation are leaning towards a solution which will be acceptable by the end user or customer. Additionally, test suites provide information about your intentions to other developers who will work on your code later.

Paolo – There are many tools one can use to test Erlang code. Can you give to our readers a brief overview over the most common testing frameworks available and explain for what kind of tests they should be used?

Michał – We typically implement test cases as Erlang functions. For unit testing we use the common_test library, which is part of Erlang/OTP. Some developers would suggest using eunit instead, but we are interested in not only unit testing, but also integration testing. Integration testing means that software modules or units are combined and tested as a group. It allows to test for requirements in performance, reliability and functionality. I believe common_test is better suited for integration testing. Having all unit tests and integration tests implemented with common_test framework makes it easier to execute and maintain.
We teach how to use common_test from unit tests to large scale testing. This covers unit test, testing with state, test groups and suites, how to configure tests, write specifications and do distributed testing. During the training we also cover the principles behind property-based testing. We use QuickCheck Mini to see how to write property-based tests: generators, properties, symbolic representation of tests, etc. This also briefly covers shrinking strategies to find errors. Property-based testing is not applicable to all testing scenarios, but it exceptionally good in protocol testing, finding edge cases and I think TDD with property-based testing can help build even better designs.

Paolo – In OOP, TDD usually goes hand in hand with mocking. I had the chance to use Meck for some of my projects and I really liked it, still many Erlang programmers don’t like mocks. What do you think about mocking in Erlang?

Michał – Mocks are good if you can’t setup the whole system, but would like to execute some unit tests anyway. While I believe it makes sense to write mocks in meck in many situations, I also like the approach of the team at Erlang Solutions, which is responsible for the MongooseIM project. For MongooseIM testing we use common_test and we setup the whole system up front. The same tests suites are run in CI against serveral different server configurations, ensuring MongooseIM behaves according to spec, regardless of the backends used for storage, etc.
The reason why some Erlang programmers don’t use mocks that much is because it is so easy to setup an Erlang/OTP system that it sometimes pays off to test against a real one, not a partially-mocked one.
I believe meck works great when testing library code, especially in tandem with QuickCheck. Here, the boundaries of your library are well-defined, and you can verify (for example) that a particular internal component always receives messages corresponding to the data that’s coming in from outside. Or, alternatively, you can mock some bit of internal state and verify that the whole system satisfies a set of properties when it’s in that particular state.

Paolo – In your opinion, what are the main resources (e.g. online documentation or books) an Erlang developer interested in TDD should take a look at to grasp these concepts in a better way?

Michał – Each Erlang/OTP library has a user’s guide and for me it is often a starting point when I need to learn something new. For example you can find the Common Test User’s Guide at
For property-based testing there are quite a few articles on Erlang Central, see here
The best way to grasp these concepts is to practice them. One can contribute a test case to an open source project or try TDD with his/her next hobby project and see what happens. When you try TDD for the first time there will be a lot of questions arising and then you are sort of forced to find an answer to your questions – that is the best way to understand the concept. Ideally you would have someone experienced sitting next to you and answering your questions, but the social networks at Erlang Central or IRC channels are also good fellows.

Paolo – There aren’t many books or blog posts about best practices or real world examples of TDD and testing in Erlang. (one of my favourite is Gianfranco Alongi’s blog). Why do you think there are so few information about the topic available to the masses?

Michał – I’m not sure how to answer this question. Instead, let’s improve the situation 🙂

Talking about Erlang, Riak and Vector Clocks with Christopher Meiklejohn (@cmeik)

February 16, 2014 1 comment

Hello! Today you may read here my interview to Christopher Meiklejohn, one of the speakers at the upcoming Erlang Factory in San Francisco. Christopher is working on Riak at Basho Technologies.

Erlang, Vector Clocks and Riak!


Paolo – Hello Chris! It’s great to have another Basho Erlanger here! Can you introduce yourself please?

Christopher – It’s great to be here! My name is Christopher Meiklejohn, and I’m currently a software engineer at Basho Technologies, Inc., where I work on our distributed datastore, Riak. In addition to that, I’m also a graduate student at Brown University, in Providence, RI, where I study distributed computing.

Paolo – Before joining Basho you were working in a different company (i.e., Swipely) where you dealt with Ruby code. Did you already know Erlang when you started at Basho? How would you describe the switch between these two languages?

Christopher – During the time I was at Swipely they had Riak deployed in production, which was what initially got me interested in Basho, Riak, in particular, Erlang. When I joined Basho, I knew very little Erlang and spent my first few weeks at the company learning it.

That said, I love Erlang as a language and as platform to build application on. I wouldn’t necessarily say that the change from Ruby to Erlang was anything that was unexpected, specifically because I already had functional programming experience using languages like Scheme and Haskell.

Paolo – Rubyists tend to be addicted to TDD. Were you able to maintain such a good practice also when coding Erlang?

Christopher – Well, I’ll start with a disclaimer. I was primarily responsible for the introduction of behavior driven development at Swipely for feature development, in addition to promoting pair programming within the development team.

That said, testing and verification of software is a very interesting topic to me.

While I believe that all software should be properly tested, I’ve never been particularly dogmatic about when in the cycle of development testing is performed: whether it’s done during development to guide the design of the software or whether it’s done afterwards to validate the authored components. I do, however, have one major exception to this rule: when attempting to reproduce a customer issue and validate a fix for the issue.

This is purely a pragmatic decision that’s come from working on large scale distributed systems: testing and verification of distributed systems is extremely hard given the number of cooperating components involved in completing a task.

At Basho, we take two major approaches to testing Riak: integration testing using a open source test harness we’ve developed that allow us to validate high level operations of the system, and QuickCheck for randomized testing of smaller pieces of functionality.

Paolo – At the upcoming Erlang Factory in San Francisco you will give the following talk: “Verified Vector Clocks: An Experience Report”. Can you introduce in a few words the arguments you will treat during the talk?

Christopher – My talk is going to look at an alternative way of asserting correct operation of software components, commonly known as formal verification.

The talk will specifically focus on modeling vector clocks for use in the Riak datastore using an interactive theorem prover called Coq. This allows us to assert certain mathematical properties about our implementation, and perform extraction of the component into Erlang codewhich we can directly use in our system.

Paolo – Who should be interested in following your talk and why?

Christopher – Given the topics involved, I’m planning on keeping the talk pretty high level and will touch a variety of topics: the theorem prover Coq, which implements a dependently-typed functional programming language, the basics of using Core Erlang, a de-sugared subset of the Erlang programming language, and how we put all of the pieces together.

Paolo – Lamport’s vector clocks are well known by people working in fields connected to distributed systems. Can you explain briefly what they are and in what fields they can be used?

Christopher – Vector clocks provide a model for reasoning about events in a distributed system. It’s a bit involved for this interview to get into the specifics about how they work and when they should be used, so I’ll refer to you two excellent articles written by Bryan Fink and Justin Sheehy of Basho.

“Why Vector Clocks Are Easy”

“Why Vector Clocks Are Hard”

Paolo – About the application vvclocks, are you planning to keep the development on? If so how can people contribute?

Christopher – At this point, the project mainly serves as a playground for exploring how we might begin to approach building verifiable software components in Erlang. What has been done so far is available on GitHub, it’s actively being worked on by myself as my time allows, and if you’re interested in helping to explore this further, feel free to reach out to me via e-mail or on Twitter.

Talking about Erlang and Agile Methodologies with Gianfranco Alongi

October 21, 2013 Leave a comment

Hello! Today in this blog you can read my interview to Gianfranco Alongi. Gianfranco is a Senior Software Developer at Ericsson with a strong passion for Erlang, Extreme Programming and Agile Methodologies. I am sure you will enjoy his answers 😀

Erlang, TDD, XP, agile….what else?

Paolo – Hi Gianfranco! It’s a pleasure to have you here today. Can you please introduce yourself to our readers?

Gianfranco – Hi, and thank you! I’m honored to be interesting enough to be mentioned in this blog!
My name is obviously Gianfranco, but my full name is Gianfranco Franco Alongi, the middle name is a relic from the laws regulating concatenation of first names.
I have always felt a deep satisfaction in programming and problem solving involving abstraction through rule sets. I get a feeling of emotional purification when crystalizing a concept, or even a crude feeling of something into a formalization that can be analyzed, executed and mechanized. I can only imagine this is what Vulcan[1] ‘enlightenment’ feels like, when you see a clear path through reality, a sense of very vivid focus and understanding.

I am a Senior Software Developer at Ericsson, doing Erlang and other things, such as lecturing about good Design, Clean Code, TDD and Software Craftsmanship. I get paid to do Erlang, but my cognitive breath mint equivalent is APL, Haskell or CLISP. I have lately got totally hooked on APL, and will travel to Florida the 19th to hold a workshop on TDD and present a Testing Library[2] I developed for the APL community.

To me, programming is a hobby, and I get paid to do this hobby during the day, but do my hobby without pay during the rest of the day (don’t tell my managers: but I would probably do the same thing even if I was not paid ; ))

My mind is to intellectual challenges what a husky is to physical exercise, I need it every day, and a lot of it. If I go without it for too long, I get restless and depressed.

Paolo – Would you like to tell us something more about your personal experience with programming and especially with Erlang? How did you start using it?

Gianfranco – Ah, yes. I got into contact with programming through my father. He worked as an IBM mainframe developer for many years, and we always had lots of books and stuff at home. He had a whole shelf with RPG, Assembly and instruction sets for different architectures. However, none of this was interesting to me. I got going with Quick Basic in 7th grade (I must have been 12 at the time), and wrote some useless stuff like text adventures.

From there, it moved on quite steadily, and in high school (Gymnasiet in swedish) – I had a math teacher who handed me a (gasp!) Pirated Copy of a Redhat enterprise edition. This is where I got serious with C++ for a while. I was now 15 and got a lot of help by this man. I knew that this was what I wanted to do! This felt so right. The programming.

When I later moved to Gothenburg, and studied at Chalmers, I met John Hughes, a very influential man with a keen sense for Functional Programming.
During this time I did a lot of Haskell, it was the main weapon of choice, but in one of John’s courses, we just happened to glance at Erlang and this was enough to catch my interest. I got hooked. And since that day, I’ve been doing it. For some reason, I have never felt that C, C++, Java, or C# has the right ‘feel’.
My cognitive mind has chemistry issues when it comes to those languages, but Haskell, Erlang, CLISP and now APL has been like hanging out with a really good friend. It’s a silent understanding between two friends. It is beautiful.

Leaving Chalmers, I was contacted by Ulf Wiger, and I started working for Erlang Solutions.

Paolo – You had the opportunity of being an Erlang developer in two of the biggest Erlang companies out there: Ericsson and ESL. Can you tell us something more about these two experiences?

Gianfranco – Erlang Solutions is a company with a lot of young talents and a lot of opportunities. You can be sent to Mexico, work with people in the USA, and basically see and do anything, as long as you are willing and able. This was a fun and interesting time, moving to London, leaving Sweden and meeting a lot of new friends. As ESL is mainly a contractor company, you get to work on a lot of different projects, this suited me well, and I loved the high pace. It is an environment where the fast movers and strong fighters can grow quickly, accumulating a strong CV with various technologies.

Ericsson is different from this. It is a corporation, thus,  by default, the pace is lower. Much lower. Ericsson does not attract the passionate developers as well as smaller companies like ESL, and there can be a lot of bureaucracy which prevents the fast movements I was used to. However, Ericsson, being a large corporation, has the money  to support and lift the passionate developers on its strong shoulders, and it can be a very different experience based on different managers. All my managers have been great, and value skill and craftsmanship, giving me the opportunity to act with a lot of freedom – and the accompanying responsibility to go with that freedom.

At the end of the day, it is us, the developers who form the culture we live in, the wrong people can make gold turn to lead even in the best places. If we are willing to change ourselves, we can do anything.

Paolo – In your current position at Ericsson you are also teaching Extreme Programming values and principles. Even though I know Ericsson has a solid story on agile methodologies I have to ask: is it difficult sometimes to advocate agile principles in such a big company?

Gianfranco – Yes.

Like most large corporations, the ‘Agile Transformation’ is first hand an adoption of ceremonies and not really about the governing values and principles. What should be a common understanding and discussion on values and goals, becomes quickly an act of doing the right things, instead of reflecting on why we do things, and how we do them. My belief is that part to blame for this,  is that Agile is being pushed down from the top, and not being something perceived necessary from the largest part of the organization.

I have yet to meet a developer who is positive about Agile. Few have even heard the term Agile Software Development, and even fewer know about XP. We have a large legacy of Telecom experts, and a dwindling few who are Software Developer Experts. As a result of this, few care how things are done, the majority cares for doing things. And, as you know – the price is paid in sweat, bugs, and blood.

The only way to go fast – is to go clean.

Paolo – In the company where I work, Kent Beck’s book on XP is a must-read  book. Beck states that XP helps developers to deliver better software. What do you think about this sentence?

Gianfranco – I agree.

My only remark is that we must never get stuck in one particular school of thought and shall always explore, educate ourselves and invest in our own career as Software Craftsmen. It is not only  a matter of professionalism, but also a matter of survival. By learning new practices and principles from others, if I can reduce my own cognitive load by using a certain technique[3], and therefore spend more time optimizing for maintainability, it is definitely worth the time and effort to learn.

We all leave a legacy behind us, daily.  If I take an extra hour refactoring my code, after passing all the tests and removing
duplication, it may seem like a large cost, but I know that in my unit, with ~200 developers, if I can reduce the time they spend
reading to comprehend it, there is an economy of scale that makes a good case to optimize for maintainability.

To me, XP is a lot about being a good developer with great practices[4], delivering value and being a pleasant man to work with.
The ‘team’ is very important to me, and I believe the best place to work at, is a place where you feel that you go to work with friends, the kind of people you feel would have your back in a Zombie Apocalypse.

Paolo – Another great book by Beck is Test Driven Development By Example. When I read it I really appreciated the part about eliminating the fear using tests. I know you also appreciate this approach, so how would you encourage a developer to start adopting TDD?

Gianfranco – My best tip to learn anything, is to do it during dedicated practice time. Children are fearless learners, they just do, and fail, and do, and fail. Eventually the feedback mechanisms allow us to tune ourselves, and we start succeeding more than failing.

With dedicated practice time, there is absolutely no pressure to succeed, and so, we loose the fear. Fear is the mind killer that puts the mind into an accelerated mode of anger and self pity, instead of the relaxed state necessary to tune properly on the feedback.

 – Do a Code Dojo together with team mates
 – or just book a 2 hour slot alone, at home.

Start by reading about TDD, and then choose a small practice problem, maybe a Kata[5][6] or any other problem you can think of.
The main point is that it is not the problem in itself that is important, it is the practice.

It does not matter that you do not finish anything, is it the journey, and the act of noticing what you notice, that is the important bit.

Once you feel that you have a grip on TDD, then you can apply it on production code.
Because if you have to get stuck, if you have to fail, do it in a safe place, don’t do it during work time.

Paolo – I appreciated very much your blog posts about TDD and Erlang. What are in your opinion the best tools an Erlang developer can use for testing his code? EUnit? Common Tests? Something else?

Gianfranco – I do not have a favorite, to me they are tools which apply well for their respective tasks. The only thing I am very careful about, is the feedback time the tool gives me.

I always use EUnit for Unit Testing.

Then I can use Common Test for Function Testing, but if the specific test case would take 20 minutes to get into place properly with CT, and I can do the same thing in 2 minutes using a bash script with netcat, then I go for the speed choice.

In my unit, we have a  different tool which is based on top of CT, but with it’s own syntax. Mostly I try to avoid it, and the straw that broke the camels back, was when I could test a certain use-case by manual configuration and some bash’ing, in just under 10 minutes, and we had tried achieving the same thing using this tool, for 3 days.

Paolo – What do you think about continuous integration and continuous development? Do you recommend any specific framework or service for Erlang code? 

Gianfranco – I think they are necessary practices that give a lot of value and make life easier. By exposing complexity early, and dealing with stress up front, we remove the pressure of doing integration and delivery later in the project.

No recommendation, sorry.

It is the doing of the work that exposes what needs to be done.

Paolo – Last question: emacs, vim or what else? 😀 

Gianfranco – Emacs, and vim when there is no emacs. I use this together with Tmux, and the no-mouse environment I use, enables a very high bandwith between my brain and the computer.

[1] Star Trek Reference
[3] such as TDD
[4] Yes, I did it, I stole the quote ; )

Four years of Erlang blogging!

September 12, 2013 Leave a comment

Hello! September 2013 has come and here I am once more to give you some information about another year of Erlang blogging 😀

Would you like to know something more about what I posted in this blog during 2013? Are you sure? Well, just keep on reading!

I can’t recall every single post I wrote this year, so I have to ad lib during this summary.

Since I noticed that you readers appreciate my interviews to famous Erlangers I kept on writing this kind of posts. I think nobody will be offended if I say that two of my favourite interviews this year were the one to Kenji Rikitake and the one to Steve Vinoski. I obviously want to thank all the others Erlangers that accepted my request for an interview and I hope that you had the chance to read at least some of their inspiring ideas and thoughts!

As promised during 2012 I tried to transform this blog into a space where Erlangers can get useful information about Erlang projects, events and books. In this sense I had the opportunity to write my impressions about the bookLearn You Some Erlang(thanks No Starch Press) and my thoughts about “Erlang by example with Cesarini and Thompson” (thanks to O’Reilly).

I also promoted Erlang Conferences all around the world and I hope that many of you attended the  EUC2013 or the recent Erlang Camp in Amsterdam (or the one that will be held soon in Nashville!).

Some posts were as usually  more technical, in this sense I enjoyed very much writing the one about TDD and kata, the one about the cost in terms of time you have in your supervisor when spawning multiple gen_servers. I also liked sharing with you the most interesting Erlang articles I read online lately in my recent post.

That all! As always I want to thank all you guys for your support and patience. Hope you will keep on following my blog during these last months of 2013 and during 2014! Have a nice Erlang year!

Categories: English, Erlang Tags: , , , ,

Interesting stuff to read about #erlang

August 25, 2013 3 comments

Hello there! 

Even though I haven’t been writing in this blog very much during the last moths, I had the chance to read many new (and old) interesting blog posts, articles and tutorial about Erlang.

Some of the stuff I had the chance to read was really well done and inspiring, therefore I would like to share these contents with you. In this blog post of mine I am going to make a list of the 4 articles that I loved most, with a brief description for each of team. Let’s start then!

Interesting Erlang stuff you should take a look at!


Here is my brief list; as I did in one of my previous blog posts I would like to remember that the order of the links is totally random!

  • Create and Deploy Your Erlang/Cowboy Application on Heroku in 30 Minutes: In this blog post, Roberto Aloi explains how to create and deploy easily a web application written using Erlang and Cowboy. I liked this article very much: Roberto is one of the most famous Erlangers out there and even though the application he presents is really easy it’s always a pleasure to read some of his code. Moreover the part related to deploy focuses on Heroku the well known cloud platform, showing how easy it is to deploy our Erlang application there.
  • Continuous Integration for Erlang With Travis-CI: continuous integration (CI) is a powerful tool. While I was searching for a good CI service to be used with one of my Erlang projects I ended up reading this nice blog post  by Ward Bekker. In his tutorial Ward explains briefly what are the main tool we have in Erlang to automate our tests and teaches how to connect a public GitHub repository to Travis-CI. I really liked this blog post, and if you are new to CI I suggest you to read as well this article by Martin Fowler: Continuous Integration.
  • Meck and Eunit Best Practices: TDD and testing in general are one of the things I am trying to learn more in these months. Even though this post by David Reid is not very recent (2011) I suggest you to read it if you want to learn more about Meck, the most famous Erlang mocking library written by Adam Lindberg.  Once more, if you are new to mocking and so on, I suggest you once more to read a great article by Martin Fowler: Mocks Aren’t Stubs.
  • A Week with Elixir: That’s true, Elixir is not Erlang, but I think we all should read what the great Joe Armstrong  thinks about this new interesting language written by José Valim. In his blog post Joe gives his impressions about Elixir and its syntax, providing code samples and really wonderful insights. If you want to know more about Elixir you can go to the official web page or consider buying this book by Dave Thomas.

And that’s all folks! I hope you will enjoy these stuff as much as I did! 

Improving your Erlang programming skills doing katas

June 10, 2013 7 comments

There is one sure thing about programming: you should try to improve your set of skills in a regular way. There are several different methods to achieve this kind of result: reading books and blogs, working on your own pet project and doing pair programming are all very good examples of this, but today I want to introduce you code kata. What is a kata? Well, since you ask, you won’t mind if I digress for a while first!

What is a kata?

In Japanese, the word kata is used to describe choreographed patterns of movements that are practised in solo or possibly with a partner. Kata are especially applied in martial arts because they do represent a way of  teaching and practicing in a systematic approach rather than as individuals in a clumsy manner. If the concept of kata is still not clear (shame on me!) you just need to watch again the movie Karate Kid. For the whole movie Mr. Miyagi San teaches Daniel LaRusso the importance of kata and we know that Miyagi San is always right!

The basic concept behind kata is fairly simple: if we keep on practicing in a repetitive manner we can acquire the ability to execute movements without  hesitation and to adapt them to a set of different situations without any fear. Pretty cool uh?

Coming back to the good old world of software developers (and especially Erlang ones) we may ask ourselves: “how can we apply the concept of kata to our daily routine?”. David Thomas (one of the authors of “The Pragmatic Programmer”) introduced  the concept of Code Kata which is a programming exercise useful to improve our knowledge and skills through practice and repetition. The interesting point of code kata is that usually the exercises proposed are easy and can be implemented on a step-by-step fashion.

Let’s do Kata togheter Daniel san!

The kata I will show you today is the FizzBuzz one. In this post we will focus only on the initial parts of stage 1: the rules can be found at Coding Dojo, but I think I will rewrite them here for the lazy ones 🙂

  • write a program that prints the numbers from 1 to 100
  • for the multiples of three print “Fizz” instead of the number
  • for the multiples of five print “Buzz” instead of the number
  • for numbers which are multiples of both three and five print “FizzBuzz”

I will solve the FizzBuzz kata using TDD and this means that I will follow this pattern during my coding:

  1. write a test using Eunit
  2. run the test -> it fails
  3. write the code to make the test pass (dumb solution)
  4. run the test -> it passes
  5. refactor
  6. go to step 1

Let’s start coding then!

In this post I will write the tests and the logic inside the same file even though I know that this is not a good practice. Remember: you should never mix logic and tests in the same file. Usually what we do in Erlang is creating a test directory at the same level of ebin and src and save all our tests there, anyhow this is somehow out of the scope of this article which is about kata and I want to write this post only using one Erlang file, so forgive me for this horrible sin and let me start with our kata!

Let’s do Kata togheter Daniel san! (This time for real)

Let’s start by writing a first EUnit test where we ensure that given a number we return that number as a string:


%% Test that given a number we return that number as a string
normal_number_test() ->
    ?assertEqual("2", evaluate(2)).

Let’s watch our test fail with pleasure now:

1> c(fizzbuzz).
2> eunit:test(fizzbuzz).
fizzbuzz: normal_number_test (module 'fizzbuzz')...*failed*

  Failed: 1.  Skipped: 0.  Passed: 0.

Rember a failing test is a good news here, because as Kent Beck says: “failure is progress”. Our first test is failing for an obvious reason: we don’t have a function evaluate/1 in our module, so we can start by coding a dumb implementation for evaluate/1 that makes our test pass.



evaluate(_Num) ->

%% Test that given a number we return that number as a string
normal_number_test() ->
    ?assertEqual("2", evaluate(2)).

Let’s test it:

3> c(fizzbuzz).
4> eunit:test(fizzbuzz).
  Test passed.

Success! Our test is passing, but the implementation is pretty naive. What if we focus on refactoring then? We can change the function evaluate/1 as follows:

evaluate(Num) ->

Let’s see if our test is still passing after the refactoring:

5> c(fizzbuzz).
6> eunit:test(fizzbuzz).
  Test passed.

Good job! We have our first function and it passes the test. What about adding a new functionality to our code? No wait! The real question is: what about creating a new test? Here we are:

%% Test that given a number divisible by 3 we return the string "Fizz"
divisible_by_3_test() ->
    ?assertEqual("Fizz", evaluate(3)).

Let’s recompile and test:

7> c(fizzbuzz).
8> eunit:test(fizzbuzz).
fizzbuzz: divisible_by_3_test...*failed*
                     {expression,"evaluate ( 3 )"},

  Failed: 1.  Skipped: 0.  Passed: 1.

As expected the test is failing, in fact we didn’t add any new functionality to our code and therefore a failure is still a good news. Let’s make the test pass then!

This is the code you may have after implementing the aforesaid “Fizz” functionality. I believe this time we can skip a dumb solution and provide the real one as follows:



evaluate(Num) when Num rem 3 =:= 0->

evaluate(Num) ->

%% Test that given a number we return that number as a string
normal_number_test() ->
    ?assertEqual("2", evaluate(2)).

%% Test that given a number divisible by 3 we return the string "Fizz"
divisible_by_3_test() ->
    ?assertEqual("Fizz", evaluate(3)).

Let’s now test it:

9> c(fizzbuzz).
10> eunit:test(fizzbuzz).
  All 2 tests passed.


Our code behaves pretty well right? At this point we should do some refactoring (of both code and tests) and then add tests and implementations for the Buzz and FizzBuzz cases. Moreover we should add a function that prints all the numbers from 1 to 100 on screen but I think I will leave all this stuff  to you as homework for a couple of reasons:

  1. I don’t like writing blog posts too long, they tend to make my readers take a nap
  2. I don’t like writing blog posts with wall of code either, they tend to make my blog uglier 
  3. I guess you may want to try solving this kata by yourself 🙂 

This is all I have to say about the FizzBuzz kata…or not?  Well, I can add some useful information here: