コメント削除のテストと実装を記述する: 小林研 Rails Tips (70)

このページの内容は以下のリポジトリに1日遅れで反映されます(記事執筆前に前日分をコミットしています)。

https://github.com/hkob/hkob_blog

はじめに

Rails Tips の 70 回目です。ガイドにはないのですが、コメント削除のテストと実装を追加します。

Rails をはじめよう - Railsガイド

コメントを編集する

現在、comment を表示している部分テンプレートを以下のように変更します。

  • コメントを編集の後ろにコメントを削除するリンクを追加します。
- if comment == @comment
  = render "articles/comments/form"
- else
  - %i[commenter body].each do |attr|
    %p= t_ars Comment, attr
    %p= comment.send attr
  %p= lotfp article_path(@article, comment_id: comment.id), title: "コメントを編集"
  %p= destroy_lotfp article_comment_path(@article, comment), Comment

views/ja.ymlarticles.comments.destroy.title の翻訳テキストを追加します。

ja:
  articles:
    index:
      title: 記事一覧
    show:
      title: 記事詳細
      link_title: 表示
    new:
      title: 記事作成
      link_title: 追加
    edit:
      title: 記事更新
      link_title: 編集
    destroy:
      link_title: 削除
    comments:
      destroy:
        link_title: コメントを削除

このままだと更新用の form と新規用の form の両方が表示されてしまうので、new_record でなかった場合には、Add a comment より下を表示しないようにします。

- if @comment.new_record?
  %h2 Add a comment:
  = render "articles/comments/form"

あとは実際の処理を記述するだけです。まずはテストを記述します。

  describe "DELETE #destroy" do
    subject { -> { delete article_comment_path(article, object) } }
    it_behaves_like "レスポンスコード確認", 303
    it_behaves_like "オブジェクトが1減るか?", Comment
    it_behaves_like "リダイレクト確認"
    it_behaves_like "Notice メッセージ確認", "コメントを削除しました。"
  end

後は実装を記述します。まずは comment を先に取得するために、take_one に destroy を追加します。

before_action :take_one, only: %i[update destroy]

その後、実際の削除処理を記述します。see_other は必ず忘れないようにします。

  def destroy
    @comment.destroy
    redirect_to @article, notice: notice_message(Comment), status: :see_other
  end

おわりに

これでガイドから脱線した部分は終わりです。次はガイドの通り concern による共通部分の記述に戻ります。