Skip to content

Commit

Permalink
ユーザーを指定して取得できるようにする
Browse files Browse the repository at this point in the history
  • Loading branch information
1021ky committed Nov 17, 2024
1 parent 828669c commit 8ce6f43
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 13 deletions.
10 changes: 10 additions & 0 deletions app/controllers/api/users_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ def index
render json: users
end

def show
id = get_user_params
user = XUser.find(id)
render json: user
end

def create
validated_param = create_user_params
res = XUser.create!(validated_param)
Expand All @@ -18,6 +24,10 @@ def create

private

def get_user_params
params.require(:id)
end

def create_user_params
params.require(:user).permit(:email, :name, :password)
end
Expand Down
2 changes: 1 addition & 1 deletion config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
# namespaceが定義されると、namespaceで指定されたシンボル名のパスの下でアクセスできるリソースを定義できる
namespace :api do
# #の前がコントローラー名、#の後がアクション名
resources :users, only: %i[index show create update destroy] # apiなのでnew editは除く
resources :tweet, only: %i[index create]
resources :users, only: %i[index create]
end

namespace :admin do
Expand Down
8 changes: 6 additions & 2 deletions spec/factories/x_users.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
FactoryBot.define do
factory :x_user do
sequence(:email) { |n| "test_user#{n}@test.com" }
sequence(:name) { |n| "foo#{n} bar#{n}" }
transient do
custom_email { nil }
custom_name { nil }
end
sequence(:email) { |n| custom_email || "test_user#{n}@test.com" }
sequence(:name) { |n| custom_name || "foo#{n} bar#{n}" }
end
end
22 changes: 12 additions & 10 deletions spec/requests/users_spec.rb
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
require 'rails_helper'
# This file contains request specs for the Users API

RSpec.describe "Users", type: :request do
RSpec.describe "Users API", type: :request do
shared_context "DBにユーザー情報があるとき" do
let!(:user1) { create(:x_user) }
let!(:user2) { create(:x_user) }
end

describe "GET /api/user" do
context "ユーザー情報がDBにあるとき" do
let!(:user) {create(:x_user)}
it "ユーザー情報が取得できる" do
p api_users_path
get api_users_path
expect(response).to have_http_status(:success)
end
describe "GET /api/user endpoint" do
include_context "DBにユーザー情報があるとき"
it "ユーザーIDを指定して取得できる" do
get api_user_path(user1.id)
expect(response).to have_http_status(:success)
expect(JSON.parse(response.body)["id"]).to eq(user1.id)
end
end
end
Expand Down

0 comments on commit 8ce6f43

Please sign in to comment.