Translate between code and Gherkin with AI

A raven is translating from one language to another

Part 2 of 2

Read Part 1

In this article about “AI-learning (E-learning 3.0)” series, we delve into translation of code, to make it easier to understand. To show that AI is also about learning and not only automation.

What is Gherkin

Gherkin is a domain-specific language that makes it possible to describe software behaviors in a human readable syntax. It’s primarily used to write structured tests that can be understood by non-technical stakeholders, making it a crucial tool in Behavior-Driven Development (BDD).

We usually write Gherkin language with: Given, When, and Then.

Translating code to Gherkin

Let’s take some Python code:

number1 = 1
number2 = 2
result = number1 + number2

Let’s make ChatGPT 3.5 translate the code to Gherkin and back:

I have the following python code, and I would like you to add Given, When, Then comments into it, so they explain the code:
number1 = 1
number2 = 2
result = number1 + number2

And the result is:

Translating from Gherkin

Let feed ChatGPT 3.5 with:

Can you please translate the following text into Python?
# Given there are two variables named numbers with values: 1 and 2
# When they are added together into a result variable
# Then the result variable must be printed.

It will give the following output:

Isn’t Given, When, Then for testing only?

It is for testing, but not only.

Given, when, then is a fantastic way to describe processes, and this is how LEGO manuals work and even IKEA.

  • Given You have the following LEGO bricks (don’t start without them).
  • When a some of the bricks are assembled in a specific way.
  • Then a specific result must be achieved.
  • When the next bricks are added.
  • Then the next result must be achieved.
  • Then the final result must be achieved.

It has been working well for LEGO and IKEA for many years.

Code is also an automated process.

By adding given, when, then comments into my code, it can make me structure my code much better.

Let’s take the following example:

# given
number1 = 1
number2 = 2

# when
result = number1 + number2

# then

Under the given: I can structure my variables or deal with null-pointers and other errors.

Under the when: I can do what is needed by the code.

Under the then: I can handle the clean the output and return it.

This makes our code clean and easier to understand.

And when it is not possible to structure code like this, then maybe it is a sign, that the code needs to be split up into smaller parts and simplified!

Want to read more?

Follow the discussion on LinkedIn

Take the following lesson:

or the full course:

Comment below or on here:

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit exceeded. Please complete the captcha once again.