TDD with Livebook

Adolfo Neto - Apr 27 '22 - - Dev Community

I have just published a video about doing TDD with Livebook:

If you are not a video person, take a look at the notebook here.

If you can run an instance of livebook, click here:

Run in Livebook

The code I typed was that of a very simple calculator. Every function was written after a test for that function was written.

defmodule Calculator do
  def add(a, b) do
    a + b
  end

  def multiply(a, b) do
    a * b
  end
end
Enter fullscreen mode Exit fullscreen mode

Unfortunately, Livebook seems to force us to put the tests below the code that is being tested.

And, as Bro0klin Myers explained here, you have to add:

ExUnit.start(auto_run: false)
Enter fullscreen mode Exit fullscreen mode

to the beginning of your test code.

You also have to put this line in your test module:

  use ExUnit.Case, async: false
Enter fullscreen mode Exit fullscreen mode

And you have to finish your test code with this line:

ExUnit.run()
Enter fullscreen mode Exit fullscreen mode

The content for the test code cell is:

ExUnit.start(auto_run: false)

defmodule CalcutorTest do
  use ExUnit.Case, async: false

  describe "Testing the addition function" do
    test "2 plus 3 is 5" do
      assert Calculator.add(2, 3) == 5
    end

    test "2 plus 2 is 4" do
      assert Calculator.add(2, 2) == 4
    end
  end

  describe "Testing the multiplication function" do
    test "2 times 3 is 6" do
      assert Calculator.multiply(2, 3) == 6
    end

    test "2 times 20 is 40" do
      assert Calculator.multiply(2, 20) == 40
    end
  end
end

ExUnit.run()
Enter fullscreen mode Exit fullscreen mode

What do you think? Is it a good idea to do TDD with Liveview?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .