LoginSignup
3
2

More than 3 years have passed since last update.

【Rails】RSpecでモデルのテストをする

Posted at

概要

モデルのテストの記述方法を解説します

詳しくはRSpecの公式サイトのモデルに関するページを参考にしてください
今回は一例としてPostモデルのテストを解説します。
前提としてPostにはアソシエーションされたCommentモデルが存在します。

spec/models/post_spec.rb
require "rails_helper"

RSpec.describe Post, :type => :model do
  context "with 2 or more comments" do
    it "orders them in reverse chronologically" do
      post = Post.create!
      comment1 = post.comments.create!(:body => "first comment")
      comment2 = post.comments.create!(:body => "second comment")
      expect(post.reload.comments).to eq([comment2, comment1])
    end
  end
end

基本はRubyの書き方と同じです。コントローラーの記述する感覚で書きます。

  • post = Post.create!

    • postを作成、保存します
    • createメソッドはnew+saveです
    • !をつけると保存できなかった時にその原因を出力してくれます
  • comment1 = post.comments.create!(:body => "first comment")

    • postに紐づいたcomment:body => "first comment"で作成する
    • comment2も同様です
  • expect(post.reload.comments).to eq([comment2, comment1])

    • post.reload.commentsの値が[comment2, comment1]と一致するかどうかを確かめる
    • post.reload.commentsreloadはデータベースの値を再び取得するためのメソッドです

以上がモデルのテストの記述方法の一例の解説です。
これを元に自身のアプリケーションにも適応し、テストしてみてください。

疑問、気になるところがございましたら、質問、コメントよろしくお願いいたします!!

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2