Test a Rails API application with RSpec
Below are steps to follow
- Adding rspec into the app gemfile:
-> gem 'rspec-rails', '~> 6.1.0' into dev/test group
-> install the gem by running: bundle install
-> run: rspec to verify - Init rspec in the application
-> run this command: rails g rspec:install - Now create a folder /spec/requests
- Create a file called money_records_spec.rb with following
- Run the tests by command: rspec
- Adding FactoryBot to gemfile
-> gem 'factory_bot_rails' into dev/test group
-> bundle install - Now creating a folder /spec/factories, then a file money_records.rb
- Continuing to edit the test file as below
require 'rails_helper'
RSpec.describe 'Money Records API', type: :request do
describe 'GET /money_records' do
it 'returns a list of money records' do
FactoryBot.create(:money_record, event_type: 'income', value: 100, event_date: Time.now, note: 'record 1')
FactoryBot.create(:money_record, event_type: 'income', value: 200, event_date: Time.now, note: 'record 2')
get '/money_records'
expect(response).to have_http_status(:success)
expect(JSON.parse(response.body).size).to eq(2)
end
end
end - Run rspec and verify