Test a Rails API application with RSpec

Below are steps to follow

  1. 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
  2. Init rspec in the application
    -> run this command: rails g rspec:install

  3. Now create a folder /spec/requests
  4. Create a file called money_records_spec.rb with following

  5. Run the tests by command: rspec
  6. Adding FactoryBot to gemfile
    -> gem 'factory_bot_rails' into dev/test group
    -> bundle install
  7. Now creating a folder /spec/factories, then a file money_records.rb

  8. 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
  9. Run rspec and verify



Back to posts