概要
コメントモデルのテストを実装
【 使用gem】
- gem "factory_bot_rails"
テストデータの作成を手伝ってくれるGemです。
gem "faker"
ダミーデータを作成するgemgem "rspec-rails"
rspecをrails用にカスタマイズしたgem
モデルの設定とAPIの実装手順はこちら

完成形
commentモデルに対するテスト.
spec/models/comment_spec.rb
require "rails_helper"
RSpec.describe Comment, type: :model do
context "必要な値がある場合" do
let(:comment) { build(:comment) }
it "comment が作られる" do
expect(comment.valid?).to eq true
end
end
context "content が空の場合" do
let(:comment) { build(:comment, content: nil) }
it "エラーする" do
comment.valid?
expect(comment.errors.messages[:content]).to include "can't be blank"
end
end
context "article が空の場合" do
let(:comment) { build(:comment, article: nil) }
it "エラーする" do
comment.valid?
expect(comment.errors.messages[:article]).to include "must exist"
end
end
context "ユーザーがいない場合" do
let(:comment) { build(:comment, user: nil) }
it "エラーする" do
comment.valid?
expect(comment.errors.messages[:user]).to include "must exist"
end
end
end
実装手順
まずFactoryBotを用いて
.
テストデータを作成するファイルを作ります。
.
spec/factories/comments.rb
FactoryBot.define do
factory :comment do
content { Faker::Lorem.paragraph }
end
end
.
commentモデルは
.
User, Articleモデルと紐づいているので
.
FactoryBot.define do
factory :comment do
content { Faker::Lorem.paragraph }
user
article
end
end
.
このように追記することで
.
build(:comment)
attribute_for(:comment)
create(:comment)
などでcommentを作成する時に
.
UserとArticleも作成されるようになります。
.
ちなみにこれは省略形で、
本来の形はUserなら
.
association :user, factory: :user
です。
.
これで準備は整ったのでテストを書いていきます。
.
テスト対象を設定します。
.
RSpec.describe Comment, type: :model do
end
validation
とアソシエーションの設定についてはこちらに記述しています。
.
それに基づいてテストを書いていく。
.
.
テストする項目は4つ。
.
必要な値がある場合 コメントできる
user
,article
,content
(commentの中身)content
がnil
の場合 エラーするarticle
がnil
の場合 エラーするuser
がnil
の場合 エラーする
必要な値がある場合 コメントできる
.
RSpec.describe Comment, type: :model do
context "必要な値がある場合" do
let(:comment) { build(:comment) }
it "comment が作られる" do
expect(comment.valid?).to eq true
end
end
end
.
context
は条件 "必要な値がある場合"
.
it
で結果を設定 "comment が作られる"
.
{ build(:comment) }
で作られたコメントを
.
let
で変数comment
に代入
.
expect
の引数にテストの対象を指定。
.
expect(comment.valid?)
.
.to eq true
でコメントは存在しているかを判定
.expect(comment.valid?).to eq true
.
$ be rspec
.
実行してテストが通れば成功。
.
content
がnil
の場合 エラーする
.
context "content が空の場合" do
let(:comment) { build(:comment, content: nil) }
it "エラーする" do
comment.valid?
expect(comment.errors.messages[:content]).to include "can't be blank"
end
end
.
let(:comment) { build(:comment, content: nil) }
で
.
コメントを作成。
.content
をnil
に設定
.comment.valid?
コメントが存在しているか?
.
expect(comment.errors.messages[:content]).to include "can't be blank"
.
commentが作られず、エラーメッセージ"can't be blank"
と言われる。
.
article
がnil
の場合 エラーするuser
がnil
の場合 エラーする
この2つも同じで
.
let(:comment) { build(:comment, content: nil) }
.
build
のcontent
の部分を置き換えて、
.
エラーメッセージが "must exist"
に変更してあとは同じ。
.
$ be rspec
.
実行してテストが通れば成功。
.
関連記事

コメント