10 Things I wish I knew before testing my Rails Application with rspec for the first time [Part 1]

Diego Tabares
2 min readAug 22, 2020

It’s been almost a year since I started using rspec to test my Rails application and on the way I have learned a lot of things that made my life much easier.

I’ll share the first 5 most important ones along this post.

Photo by Angelina Litvin on Unsplash
  1. Follow betterspecs.org guidelines
    Lost? Don’t know if you are writing your tests “in the right way?”. Following these guidelines will help you start writing your tests in the right direction (and save a ton of rework later…… been there…). Pay extra attention to the usage of let & let! and how to describe your methods. Oh, using contexts really improves the readability too.
  2. FactoryBot
    You’ll probably need to create some test data for your tests, and that’s when FactoryBot comes really handy. This gem allows you to create sample data for all of your classes even when they have associations. It’s really easy to use, so you don’t have to worry about the learning curve. Keep an eye on the traits option, since it’s really useful too when needing to group attributes.
    Here is a link to a good cheatsheet to get started.
  3. Faker
    Ok, so you also need to figure out what to fill your sample data with…. bummer. That’s when Faker comes to the rescue, a great library for generating names, email addresses, etc. It’s also quite easy to use as well and works like a charm with FactoryBot.
  4. SimpleCov
    Once you have tests, it’s important to know what code is being covered by those tests and what you are missing. If something is being missed it could be that you don’t have a test to cover that scenario, or that simply…. that code is not being used anymore. Having a 100% coverage as a target is great to detect those cases. The best way I found to get good coverage reports is by using SimpleCoV gem. Just a quick tip, try running simplecov at the beginning of the rails_helper.rb file to make sure all your application code is getting covered.
  5. DatabaseCleaner
    If you are creating sample data for your tests and saving it to the Database, you need to make sure that you have your Database in a pristine state so every test it’s isolated from the others. Until I started using DatabaseCleaner this was a big headache for me. This gem will make sure you start with a clean Database state for each test (if you configure it correctly, so keep an eye on the documentation).

Part 2 will be coming shortly, in the meantime… Happy Testing!

--

--

Diego Tabares

Currently studying Computer Engineering @Untref. Linux and Mac user. @Independiente Fan. Proud IBMer. My opinions are my own.