0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RailsとNuxt3でtodoリストを作ろう[REST-API/Terraform/Fargate]〜その2、Rails API編

Last updated at Posted at 2023-06-05

はじめに

RailsとNuxt3でtodoリストの作り方を
初めから丁寧に説明したいと思います。

使用pcはmacを想定しています。

完成した構成図は以下の通りです。

aws_structure.png

また、githubレポジトリはこちらです。

各シリーズは以下の通りです。

RailsとNuxt3でtodoリストを作ろう[REST-API/Terraform/Fargate]〜その1、Rails基本設定編
RailsとNuxt3でtodoリストを作ろう[REST-API/Terraform/Fargate]〜その2、Rails API編
RailsとNuxt3でtodoリストを作ろう[REST-API/Terraform/Fargate]〜その3、Nuxt.js編
RailsとNuxt3でtodoリストを作ろう[REST-API/Terraform/Fargate]〜その4、TerraformECS前編
RailsとNuxt3でtodoリストを作ろう[REST-API/Terraform/Fargate]〜その5、TerraformECS後編
RailsとNuxt3でtodoリストを作ろう[REST-API/Terraform/Fargate]〜その6、Blue/Greenデプロイ前編
RailsとNuxt3でtodoリストを作ろう[REST-API/Terraform/Fargate]〜その7、Blue/Greenデプロイ後編

マイグレーションをしてみる

rails g model todo content:text
rails db:migrate

Screenshot 2023-03-26 at 20.19.40.png

クライアントツールで確認してみる

想定通りのテーブルが作られていると思います。

Screenshot 2023-03-26 at 20.27.26.png

REST APIを作ろう

rutingを作ろう

config/routes.rb
Rails.application.routes.draw do
  root "index#index"
  namespace 'api' do
    resources :todos, only:[:index, :show, :create, :destroy, :update] do
    end
  end
end

controllerを作ろう

rails g controller api::todos
app/controllers/api/todos_controller.rb
class Api::TodosController < ApplicationController
    before_action :set_todo, only: [:show, :update, :destroy]
    def index
        @todos = Todo.all
        render status: :ok, json: @todos #200
    end
    def show
        render status: :ok, json: @todo
    end
    def create
        todo = Todo.new(todo_params)
        if todo.save
          render status: :created #201
        else
          render status: :unprocessable_entity #422
        end
    end
    def update
        if @todo.update(todo_params)
            render status: :accepted
        else
            render status: :unprocessable_entity
        end
    end
    def destroy
        @todo.destroy
        render status: :accepted #202
    end

    private
    def set_todo
        @todo = Todo.find(params[:id])
    end
    def todo_params
        params.require(:todo).permit(:content)
    end
end

クライアントツールで確認しよう

index

Screenshot 2023-03-27 at 11.25.00.png

show

Screenshot 2023-03-27 at 11.26.10.png

create

Screenshot 2023-03-27 at 11.47.58.png

update

Screenshot 2023-03-27 at 11.51.42.png

destroy

Screenshot 2023-03-27 at 11.52.00.png

rspecで単体テストを実施しよう

factory_bot_railsをインストールしよう

コンテナの中に入り以下のコマンドを実行しよう。

sed -i -e '$ a gem "factory_bot_rails", "~> 6.2.0"' ./Gemfile
bundle install

factory_bot用のモデルを作ろう

rails g factory_bot:model todo

todos.rbが生成されるので、以下のようにカラムを入れよう。
{}の中は好きなコメントを入れよう。

spec/factories/todos.rb
FactoryBot.define do
  factory :todo do
    content {"testcomment"}
  end
end

モデルのテストを実施しよう

spec/models/todo_spec.rb
require 'rails_helper'

RSpec.describe Todo, type: :model do
  it "create recode" do
    todo = FactoryBot.create(:todo)
    expect(todo).to be_valid
  end
end
bundle exec rspec spec/models/todo_spec.rb

Screenshot 2023-03-28 at 10.03.24.png

コントローラーのテストを実施しよう

spec/requests/api/todos_spec.rb
require 'rails_helper'

RSpec.describe "Api::Todos", type: :request do
  describe "POST /api/todos" do
    it "check create method" do
      valid_params = { content: "test_api" }
      header_params = { "Content-Type" => "application/json" }
      expect { post "/api/todos", params: valid_params.to_json, headers: header_params}.to change(Todo, :count).by(+1)
      expect(response.status).to eq(201)
    end
  end
  describe "GET /api/todos" do
    it "check index method" do
      FactoryBot.create(:todo)
      get '/api/todos'
      expect(response.status).to eq(200)
    end
  end
  describe "GET /api/todos/x" do
    it "check show method" do
      FactoryBot.create(:todo)
      todo = Todo.all.order(id: "DESC").limit(1)
      get "/api/todos/#{todo.ids[0]}"
      expect(response.status).to eq(200)
    end
  end
  describe "PUT /api/todos/x" do
    it "check update method" do
      todo = Todo.all.order(id: "DESC").limit(1)
      valid_params = { content: "update_api" }
      header_params = { "Content-Type" => "application/json" }
      put "/api/todos/#{todo.ids[0]}", params: valid_params.to_json, headers: header_params
      expect(response.status).to eq(202)
    end
  end
  describe "DELETE /api/todos/x" do
    it "check delete method" do
      FactoryBot.create(:todo)
      todo = Todo.all.order(id: "DESC").limit(1)
      delete "/api/todos/#{todo.ids[0]}"
      expect(response.status).to eq(202)
    end
  end
end

bundle exec rspec spec/requests/api/todos_spec.rb

Screenshot 2023-03-28 at 10.06.34.png

Github actionsでテストを実施しよう

app.test-deploy.ymlにDBマイグレーション追加しよう

.github/workflows/app.test-deploy.yml
      - name: sleep for waiting launch db
        run: sleep 120s
      - name: start to db migration #<- 追加
        run: | #<- 追加
          docker compose exec apserver rails db:migrate #<- 追加
      - name: unit testting
        run: |
          docker compose exec apserver bundle exec rspec
      - name: Docker Down
        run: docker compose down

Githubで結果を確認しよう

以下のようになったと思います。

Screenshot 2023-03-28 at 10.22.33.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?