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.


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

headers = { ‘Accept’: ‘application/json’, ‘Content-Type’: ‘application/json’ }

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

# create a ticket
ticket_params = { user_id: user['user']['user_id'], title: 'test ticket', request: 'this is a test request' }
headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': "Bearer #{user['token']}" }
post '/api/v1/tickets', params: ticket_params.to_json, headers: headers
tickets = JSON.parse(response.body)

Request matchers

.to have_http_status

.to include


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