Ruby on Rails Testing with RSpec: Writing your First Tests

Tests don’t always have to be hard or scary. How writing your own tests early on as a developer can benefit you in the long-term

Warren Niu
Nerd For Tech
6 min readMay 22, 2021

--

If you’re like me, then you understand where I’m coming from when I say that I have always dreaded assessments. Perhaps it was the anxiety, the lack of knowledge, or performing under pressure (or maybe all of it…). Either way, it was a fear that I never overcame, and still haven’t overcome to this day.

However, as I’ve gotten older, I’ve become more accepting of exams and the purpose behind them. Yes, they’re still scary and always will be, but if we view them less as, “Gotcha! You’re still not smart” and more so as a measuring stick on how you’re progressing and where you need to improve, it’s not so bad.

Well, at least there’s only one way to go from here!

Testing your code should be viewed the same way.

Yes, a failing test can still be intimidating (I still can’t get over the scary and mean looking red text), but it saves us from further hardships. Think of tests as checkpoints — each test can check whether a specific feature still passes. As we scale our application and add more & more features, we want to ensure that our previous features still work. Otherwise, we would have a mess on our hands.

Imagine if we kept adding features but didn’t test our code along the way, only to find our that our code was broken and we can’t pinpoint exactly where and when it broke. We would have to go back step-by-step and test everything — it would be super inefficient & frustrating as a developer!

As a matter-of-fact, there is a whole software development approach built around this concept called Test Driven Development.

Test Driven Development (TDD)

As defined by the website Guru99:

“ TDD is a software development approach in which test cases are developed to specify and validate what the code will do. In simple terms, test cases for each functionality are created and tested first and if the test fails then the new code is written in order to pass the test and making code simple and bug-free”

As mentioned above, we write test cases for every functionality of an application, even a small function. If a test has failed, it’s up to us as developers to go back and write new code to address the issue.

It’s important to note that this concept revolves around the idea that we write and correct code before development (or writing new code). This ensures that we keep our code clean, write small amount of code each time, and avoid duplicated code.

RSpec and Common Test Types

In this article, we’ll be introduced to the RSpec gem, which is the most common tool for testing Rails applications.

There are some common testing types that you’ll encounter on your journey as a developer. They are:

  1. Model testing: Tests that models validate as they should, and that all methods work.
  2. Request testing: Tests that the controller does what it should, either for processing HTTP requests or for API endpoints
  3. Feature testing: Test web application executes browser operations, entering data in fields, clicking on buttons, and other features
  4. System testing: End-to-end testing of the application

We’ll focus on Model testing in this article.

Getting Set Up

Before we get started, we’ll need to add the rspec-rails gem to our Gemfile. We’ll also need to do a bundle install after adding this gem. This gem can be added to the Gemfile under the :development, :test section of the Gemfile.

Don’t forget to bundle install after adding!

Set up your schema to look like the following- we’ll be working with a Customer model with the first_name, last_name, and phone attribute.

Enter the following commands in your terminal to complete the setup of rspec and set up the test database

Then, enter these commands to set up the shells of test classes for the customer model and customers controller.

After these commands, the shells of two test case files will have been generated. These are:

We can now run rspec by typing “rspec” in our command line!

Writing our First Tests

Now that we’re set up, lets introduce you to some rspec specific syntax and write a few tests

Let’s break down what’s going on in the snippet above:

  1. The Rspec.describe do…end block describes what the type of object is (in our case, a model class, should do.
  2. The subject is set, which is a piece of sample data. In our case, we have a sample Customer object
  3. The “it” blocks states the expected results of the test case.
  4. The “expect” keyword states the expected results for the test, so each of the test cases has one or more expected results.

If we write a “it” block without a do…end is a test case that is pending, meaning the test hasn’t been written yet.

Let’s look at the first three tests that have a written expected result. The first test simply just tests that our customer is valid with all valid attributes.

The next two tests whether the customer has a first and last name. If it’s missing one or the other (or both), the customer will be invalid.

So how do we check for this? We can write validations in our customer model!

Searching the Rails documentation, we can use presence to check whether it’s present:

Running rspec in our command line, we should see that all of our tests are passing except for 3 pending. We’ll fix that now.

Our first pending test is similar to what we’ve seen as we want to check that a phone number is present. We can once again use the same syntax, which is to say if the value =nil, we expect the object to be invalid.

As for the remaining two tests, we can use the built-in length method to check whether that attribute is equal to 10 characters, and regular expression to check whether all the characters are numeric digits.

Looking at the Rails documentation once more, we can write some additional validations using numericality and length in our Customer model

Run rspec once more in your terminal. All of our tests should now be passing!

Conclusion

Congratulations on writing your first tests! Hopefully being introduced to some simple tests will help quell some of the fears you have for writing & passing tests. Being introduced to tests early on in your development career can certainly help you become a better developer and change your viewpoint on how tests are used.

Remember, writing numerous tests that test each and every feature will help you debug as you scale your applications.

Sources

Guru99: What is Test Driven Development (TDD)? Tutorial with Example
https://www.guru99.com/test-driven-development.html

Additional Resources

Semaphore: How to Test Rails Models with RSpec
https://semaphoreci.com/community/tutorials/how-to-test-rails-models-with-rspec

--

--

Warren Niu
Nerd For Tech

Uncovering the truths of Software Engineering one story at a time. Former Healthcare Administrator and proud dad of my Pomeranian, Nami. Based in Brooklyn, NY