2021-04-24
2021-04-24
やること宣言
gaaamii.icon
daiiz.icon
勉強中メモ
gaaamii.icon
なんかコード書くぞ
API側の修正をする
ブログ一覧ページで、/postsへのリクエストに対してpostsの全部のフィールドを入れて返してしまっている。一覧APIの場合は本文は返さないようにしたい
code:ruby
def index
@posts = Post.order(published_at: :desc)
render json: @posts
end
いまは単純にこんな感じ。
クエリパラメータとかで制御するか、すべて同じ形に修正するか迷う。
いったん同じ形で、もし本文もほしいときがあれば制御するようにすればいいや。YAGNI。
テストも書いてないからそろそろ書き始めないとなー。
おもむろにbundle exec rspecしたらなんかこけた
code:ruby
An error occurred while loading ./spec/routing/users_routing_spec.rb.
Failure/Error:
RSpec.describe UsersController, type: :routing do
describe "routing" do
expect(get: "/users").to route_to("users#index")
end
expect(get: "/users/1").to route_to("users#show", id: "1")
end
NameError:
uninitialized constant UsersController
Did you mean? UserSessionsController
# ./spec/routing/users_routing_spec.rb:3:in `<top (required)>'
ふむ。たしかにそんなコントローラはないぞ。
そもそもこのルーティングスペックってあんまり馴染みないけど、最近のRailsだとこういうのも書いたほうがいいのかしら
一応書いとこう。
書いた。
request specも書かないと。
仕事で書くときは他のテストコードからコピーして中身を書き換えるという感じだけど、今回は1発目のテストコードなのでrspec-railsのドキュメントをちゃんと見る。
ファイル名はrequests/posts_controller_spec.rbとrequests/posts_spec.rbどちらがいいのか。
コントローラスペックではないので、requests/posts_spec.rbのほうがいいような気がする。そうしよう。
code:ruby
RSpec.describe PostsController, type: :request do
describe "#index" do
it "returns an index of posts" do
get "/posts"
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)).to be_kind_of(Array)
end
end
end
とりあえずこんなん。ただ、今回の仕様変更にまつわるところをrequest specに書いていいものか
やめとくか。scopeにしてmodelのテストに書くか
Post.indexみたいなのはやしていいもんかな
You tried to define a scope named "index" on the model "Post", but ActiveRecord::Relation already defined an instance method with the same name.
だめだった。ほかのところに取られていた
こんなんでいいか
code:app/models/post.rb
scope :list, -> { order(published_at: :desc).pluck(:id, :title, :published_at) }
そういえばFactoryBot入れないとか
入れた
RSpecでexpect(array)not_to all(...)みたいなのを書きたかったけどできないっぽい。うーむ。
一旦expect(array.first).not_to (...)みたいにして一個目だけテストするようにした。
一人でやってるものだからPRにする必要なかったんだけど、差分が見返しやすいので。
あとdependabotを入れておきたい
CIの設定もしておきだいけどそこまでやる時間があるかどうか
今日は無理だった。また今度。
やったこと
gaaamii.icon
投稿一覧APIで無駄に本文まで読み込んでいたのを、タイトルと投稿日時だけに絞って読み込むように修正
Dependabot設定