このページの内容は以下のリポジトリに1日遅れで反映されます(記事執筆前に前日分をコミットしています)。
https://github.com/hkob/hkob_blog
はじめに
Rails Tips の 66 回目です。昨日追加したルーティングに相当する articles/comments_controller.rb
を追加します。
8.4 コントローラを生成する
昨日説明したように Rails ガイドでは、フラットなコントローラを使っています。一方で、ここではネストしたコントローラを作成します。
$ bin/rails g controller articles/comments create app/controllers/articles/comments_controller.rb invoke haml create app/views/articles/comments invoke rspec create spec/requests/articles/comments_spec.rb
これで作成される request spec には integration テストの雛形が入ってこないので、integration_test で上書きします。
$ bin/rails g integration_test articles/comments invoke rspec conflict spec/requests/articles/comments_spec.rb Overwrite /Users/hkob/Library/CloudStorage/Dropbox/rails/hkob_blog/spec/requests/articles/comments_spec.rb? (enter "h" for help) [Ynaqdhm] force spec/requests/articles/comments_spec.rb
作成された Request spec の先頭部分を示します。ネストした雛形だと、articles_comments
や articles_comments_path
のような本来と異なるモデルやパスが生成されてしまいます。これらを一つ一つ修正するのは面倒なので、雛形が作成された時点で一括置換してしまいます。
# rubocop:disable all require "rails_helper" # RSpec.describe Articles::CommentsController, type: :request do # let!(:articles_comment) { articles_comments :can_delete } # let!(:object) { articles_comment } # let!(:attrs) { object.attributes } # let(:not_mine) { articles_comments :not_mine } # let(:return_path) { articles_comments_path }
以下の手順で書き換えを行います。
s/articles_comment/comment/g
s/comments_path/article_comments_path/g
s/comment_path/article_comment_path/g
s/Articles::Comment$/Comment/
s/Articles::Comment,/Comment,/
s/XXX/コメント/g
この置換により以下のようにテストに使える雛形になりました。
require "rails_helper" # RSpec.describe Articles::CommentsController, type: :request do # let!(:comment) { comments :can_delete } # let!(:object) { comment } # let!(:attrs) { object.attributes } # let(:not_mine) { comments :not_mine } # let(:return_path) { article_comments_path }
おわりに
ここから実際にコメントの追加に入るのですが、Rails ガイドの書き方からかなり大きく離れるので、説明が長くなりそうです。明日しっかり記述したいので、短めなのですが今日はここまでにしておきます。