RSpecを用いたRails ApiのTest


環境
ruby:2.6.5
rails:6.0.2
macOS:Mojave(10.14.6)

事前準備
'rspec-rails','factory_bot_rails'のgemを入れておく

Gemfile
group :development, :test do
  #-- 省略 --
  gem 'rspec-rails', '~> 3.6'
  gem 'factory_bot_rails'
end

RSpecを用いたApiのテスト

apiディレクトリ内にコントローラを入れている記事を見つけられなかったので
投稿します。今回はgetのテストに絞っています。

subjectsはnameカラムだけ持つテーブルです。

controller

app/controllers/api/subjects_controller.rb
module Api
    class SubjectsController < ApplicationController
        def index
            subjects = Subject.order(id: :asc)
            render json: { status:'SUCCESS', message:'Loaded subjects', data: subjects }
        end
    end
end

factory

spec/factories/subjects.rb
FactoryBot.define do
    factory :subject do
        name { "subject test" }
    end
end

RSpec test

spec/controllers/api/subjects_controller_spec.rb
require 'rails_helper'

# Api::をつけることに注意 ここにめちゃくちゃハマった。
# 階層構造を作らない場合でもSubjectsControllerに""をつけるとエラーになるので注意
RSpec.describe Api::SubjectsController, type: :controller do

        it "全てのsubjectを取得する" do
            #subjectをファクトリから15個作成
            FactoryBot.create_list(:subject, 15)

            get :index
            json = JSON.parse(response.body)

            # 200 success が返ってきたか確認する。
            expect(response.status).to eq(200)

            # 作ったデータの数と同じ数のデータが返されたか確認する。
            expect(json['data'].length).to eq(15)
        end

end

まとめ

冒頭でも述べましたがApiとして利用しているコントローラを階層構造に分けている記事があまり見当たらず苦労しました。
同じところでハマる人が一人でも少なくなれば幸いです。
また、時間がある時にpost,create,deleteのテストも追加したいと思います。
何かおかしい点等ございましたら、コメントお願いします。
それではコロナに負けず一緒に戦いましょう!
#stay home !!