Writing a test in Ruby can come in two popular flavors, minitest and Rspec. When I was at my first ever professional gig we were using minitest, and where I’m at now we use Rspec. Minitest is the default testing library for Ruby, but in my opinion, Rspec is preferred because it has more gems and better build tools. Whichever way you decide to go however, you’ll be able to sufficiently test your Ruby code. Below is an example of both minitest and Rspec in action.
First we will look at minitest. Say we have a Teacher class with a method called “ask” which accepts a question as an argument, the method always returns “I’m not sure”. To write a test for this we have a class called TeacherTest which inherits from our minitest library. We call our test test_ask_returns_an_answer, we set teacher equal to a new instance of our Teacher class and we use the keyword assert (which comes from our minitest library) teacher.ask (here we invoke the method we want to test) == “I’m not sure”. So we are calling our method and testing that the returned response is equal to what we would expect from our method.
If we wanted to write this same test in Rspec it would look like this. We describe our class, in this case Teacher. The keyword ‘subject’ refers to our class, so in turn we expect Teacher.new.ask to equal “I’m not sure.”