Overridable Macro for exunit test cases

Radio Active Source

I am writing test cases for my application and most of my controllers contain common code for CRUDs so I have written common macro and use it inside my controllers. Test cases for all of the controllers would be written automatically. But I am confused about how to make this common code overridable so that I can override whenever I want.

defmodule Qserv.ControllerTest do
  defmacro __using__(_options) do
   quote location: :keep do
     use Qserv.Web.ConnCase, async: true
     # this kernel will give me access to current `@model` and `@controller` 
     use Qserv.KernelTest

     describe "#{@controller}.create/2" do
       test "All required fields set `required` in model should generate errors that these fields are missing -> One, two, All"

       test "Only required fields should create record and match the object"

     # defoverridable index: 2, I want to override above `describe` completely or/and the included test cases

Any help/idea how to achieve this?



answered 7 days ago José Valim #1

I am generally not a fan of the "let's do things to undo it later". It generally forces developers to keep a stack in their head of how things are added and removed later on.

In this case in particular, you are coupling on the test name. Imagine someone decides to make the "two" in "One, two, All" uppercase. Now all of the future overrides won't apply and you will have duplicate tests.

A better solution to explicit opt in what you need. For example, you can define smaller macros that you use when necessary:


Maybe you could have describe_restful! that invokes all of them. The lesson here is to have small building blocks that you build on top of instead of having a huge chunk that you try to break apart later.

PS: please use better names than the describe_x that I used. :)

comments powered by Disqus