DEV Community

chenge
chenge

Posted on

4

Simple TDD in 5 minutes in Ruby

Considering my exaggerated title, I will try to explain it briefly.

The test driven is a huge advancement from Kent Beck that enhances developer confidence and code quality and slows the developer's hair whitening. Although it has been popular for 10 years, I still see people saying that this technology is difficult. I don't think so. The technology itself is very simple. Below I use a simple example to illustrate.

Create directory

I use a simple calculator to illustrate, create an empty directory calc-tdd

mkdir calc-tdd
cd calc-tdd
touch test_calc.rb
touch calculator.rb

Now that we have the directory and two files, let's start writing the code test_calc.rb and write the test first.

Write Test

#test_calc.rb

require "minitest/autorun"

require "./calculator.rb"

class TestCalculator < MiniTest::Test
    def test_add
        calc = Calculator.new
        assert calc.add(1, 2) == 3
    end
end

After the test is finished, you can run it.

ruby test_calc.rb

The result will be reported because the code has not been implemented.

Implementation code

#calculator.rb

class Calculator
    def add(a, b)
        a + b
    end
end

Ok, run the test again and you will find the code passed. It’s simple enough, look at the watch for five minutes.

Next you can add a subtraction test sub yourself.

Follow-up can learn the usage of setup and teardown, and of course there are many things worth learning, such as RSpec.

in conclusion

TDD is a huge improvement, and the basic concept is simple. Of course, the test itself is a complex field, and there is still a lot to learn to become a test expert.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay