The ultimate rspec cheatsheet for testing Rails APIs

Test coverage

To check your test coverage, use simplecov .
Add it to your gemfile then run bundle install

gem 'simplecov', require: false, group: :test

At the very top of your spec/spec_helper.rb file, add

Run bundle exec rspec as usual to see test coverage.

Setup

At the top of each test file, add

require ‘rails_helper`

Test models

Describe a model test. For example, a user model

Create a model instance example

Create an it block for each test.

using the expect + eq matcher inside an it block

expect(user.password).to eq(‘password’)

using the to_not + be valid matcher

using the to + be valid

expect(user).to be_valid

Request specs

Describe a test block

Create an it block

Within an it block, create params and necessary headers. E.g

Make a request with the params and headers. For example, a POST request

Get the response from the request and save to a variable

Add an authorization header to a request

Putting it all together

Request matchers

.to have_http_status

.to include

length

Written by

Full-stack Engineer. Rails/Node.js/React. I love plantain chips! Reach me at Adebola.dev.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store