Ginkgo practices

Oleksandr Slynko
2 min readApr 12, 2021

Inspired by Ginkgotchas and Effective Ginkgo/Gomega.

Minimum global variables

Try not to use variables outside of the tests. It is possible to shadow variable, it is easy to miss the initial definition. It adds confusion.

And if you are using global variables, always assign the value in BeforeEach block. It is easy to find, if you are running the tests in the random order all the times.

One particular concern is the global variable `err`.

For some tests, the difference between the cases are only parameters of the function and the return type.

I have seen tests which consisted only from the single line and a bit different BeforeEach. Saving of the single line not worth adding the confusion and extra using of JustBeforeEach.

Error handling

One of the typical patterns I see in Gomega tests is the overuse of Expect(err).NotTo(HaveOccurred()) . Sometimes it is easy to track, but mostly it is just confusing. Why the error happened, what was the call. You quite often have to go inside the test to uncover the problem. It might be even worse for the cases when you expect the error and it does not happen.

If you want more context, you can read this long-running issue in Kubernetes.

GinkgoWriter

The typical way to see what is happening is to write logs. Typically, people write in stdout and do this in tests as well. This pollutes the nice output. To prevent it, use GinkgoWriter. It can be used instead of stdout and hides the output unless the test fails or you run the test in the verbose mode.

Use ginkgo binary

There is a built-in way of running tests: go test . Ginkgo supports it, but also provides its own binary. It is much better to use ginkgo . It provides several goodies: ginkgo watch , flags to randomize tests and suits, one of my favourites flags to look for the flakes -untilItFails .

I suggest using ginkgo -r -race -randomizeSuites -randomizeAllSpecs -keepGoing because it makes it easier to find any flakes you can have.

--

--

Oleksandr Slynko

Reading code for a long time, writing code for even longer.