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

require 'simplecov'
SimpleCov.start

Setup

At the top of each test file, add

Test models

Describe a model test. For example, a user model

RSpec.describe User, type: :model do
describe '# when created user is valid' do
end
end
let(:user) { User.create(name: 'test_user', email: 'test@test.com', password: 'password', password_confirmation: 'password') }
it 'checks for the presence of values in required fields' do
expect(user.name).to eq('test_user')
end
expect(user).to_not be_valid

Request specs

Describe a test block

RSpec.describe 'Users', type: :request do
end
it 'tests that an authenticated user can create comments' do
end
params = { name: 'test_user', email: 'test@test.com', password: 'password', password_confirmation: 'password' }headers = { ‘Accept’: ‘application/json’, ‘Content-Type’: ‘application/json’ }
post '/api/v1/users', params: params.to_json, headers: headers
user = JSON.parse(response.body)
headers = { ‘Accept’: ‘application/json’, ‘Content-Type’: ‘application/json’, ‘Authorization’: “Bearer #{user[‘token’]}” }
it 'tests that an authenticated user can create comments' do
# create a user
params = { name: 'test_user', email: 'test@test.com', password: 'password', password_confirmation: 'password' }
headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' }
post '/api/v1/users', params: params.to_json, headers: headers
user = JSON.parse(response.body)
# 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)
end

Request matchers

.to have_http_status

expect(response).to have_http_status(401)
expect(response.body).to include('not authorized')
expect(tickets['tickets'].length).to eq(2)

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