Skip to content

Commit

Permalink
API(posts)の修正をした。
Browse files Browse the repository at this point in the history
current_userをsessionで管理するようにしたのでそれに合わせた修正をした。

Grapeのhelpersブロックに定義したメソッドのモックの仕方は以下を参考にした。
ruby-grape/grape#397

Grapeでrailsで使っているsessionを使うため方法は以下を参考にした。
https://stackoverflow.com/questions/35344117/why-does-session-doesnt-work-in-grape-rails
  • Loading branch information
yukihirop committed Feb 25, 2018
1 parent a6ddba3 commit 2a8a4ea
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
20 changes: 18 additions & 2 deletions app/apis/api/v1/posts.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,26 @@
module API
module V1
class Posts < Grape::API
# 参考
# https://stackoverflow.com/questions/35344117/why-does-session-doesnt-work-in-grape-rails
use ActionDispatch::Session::CookieStore, key: 'user_id'

helpers do
def session
env['rack.session']
end

# TODO: sessionに保持しておくものがuse_idでは実用的ではないので
# あとで必ず書き換える必要がある。
# faowighoiwh98haf0anwifahwioa
# こんな感じのトークンになるように
def current_user
id = params[:user_id] || params[:id]
@current_uesr ||= ::User.find(id)
# TODO: あとで必ず修正する
# sessionsのAPIを作るまではcurrent_uesrを参照したら現在のユーザー1のuser_idを設定するようにする
session[:user_id] = 1 if Rails.env.development?
return unless session[:user_id]
return @current_user if defined?(@current_user)
@current_user = ::User.find(session[:user_id])
end

def post_with_revision_params
Expand Down
10 changes: 10 additions & 0 deletions spec/apis/api/v1/posts_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ module V1
RSpec.describe Posts, type: :request do
let!(:current_user) { create(:user) }

# helpersのメソッドのモックの仕方
# https://github.com/ruby-grape/grape/pull/397
before do
Grape::Endpoint.before_each do |endpoint|
endpoint.stub(:current_user).and_return current_user
end
end

after { Grape::Endpoint.before_each nil }

describe 'GET /posts' do
let!(:posts) { create_list(:post_with_revisions, 5, user: current_user) }
let(:path) { "/api/v1/posts" }
Expand Down

0 comments on commit 2a8a4ea

Please sign in to comment.