DEV Community

Cover image for 49 Days of Ruby: Day 46 -- Testing Frameworks: Minitest
Ben Greenberg
Ben Greenberg

Posted on

49 Days of Ruby: Day 46 -- Testing Frameworks: Minitest

Welcome to day 46 of the 49 Days of Ruby! 🎉

Yesterday, we discussed why it is a good idea to write tests. Today, we'll talk a bit about how to do that using the Ruby testing framework, Minitest.

Let's see we had the following code:

def my_coffee
  "Espresso"
end
Enter fullscreen mode Exit fullscreen mode

Now, above is a pretty straightforward piece of Ruby code. The method outputs the string Espresso.

What would a Minitest look like for this method?

require "minitest/autorun"

 def test_that_coffee_is_espresso
    assert_equal "Espresso", my_coffee
end
Enter fullscreen mode Exit fullscreen mode

In the above testing method, #test_that_coffee_is_espresso we invoke the Minitest assert_equal, which takes in two arguments. The arguments are the items being compared to each other. In this case, we are comparing what I expect the output to be, and what the method returns.

When you run this test, your terminal will show you something like this:

# Running:

...................................................................... (etc)

Finished in 0.107130s, 1 runs/s, 1 assertions/s.

1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
Enter fullscreen mode Exit fullscreen mode

Meaning, your test passed!

TDD

There is a very worthwhile way of writing code called "TDD," which stands for "Test Driven Development". It is the idea that you first write the tests, defining your code's expectations, and then write the code to match those tests.

Here is an example:

def test_that_coffee_is_not_tea
  assert_not_equal, "Earl Gray", my_coffee
end

def test_that_coffee_is_espresso
  assert_equal, "Espresso", my_coffee
end
Enter fullscreen mode Exit fullscreen mode

When you run that test initially you'll see an output including the following:

1 run, 2 assertions, 2 failures, 0 errors, 0 skips
Enter fullscreen mode Exit fullscreen mode

The tests failed because there was no method called #my_coffee.

Those tests start to give us the contours of our as of yet undefined method. Now, when we want to start writing our code, we know that it should not be "Earl Gray" and it should be "Espresso":

def my_coffee
  "Espresso"
end
Enter fullscreen mode Exit fullscreen mode

Those are just a few examples of what you can do with Minitest! Check out their README on GitHub and keep on exploring.

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Top comments (0)