LoginSignup
0
0

More than 1 year has passed since last update.

モデルスペックにおける超基本的なテスト(Postモデルver.)

Posted at

RSpecのモデルスペックではバリデーションやインスタンスメソッドをテストします。
今回はバリデーションの中でも基本的なpresence: trueを取り上げてテストしてみました。

1. Postモデルのバリデーション確認

今回Postモデルにはcontentカラムが存在すること(presence: true)がバリデーションによって制限されています。

post.rb
class Post < ApplicationRecord
  validates :content, { presence: true }
end

2. モデルの要件を満たせば有効であることをテスト

itで始まる行の中にpostというインスタンスをnewメソッドで作成します。このpostのcontentカラムには「あああ」という文字列が入っています。
そしてbe_validというマッチャを用いて、作成したpostが有効であることをテストします。

post_spec.rb
require 'rails_helper'

RSpec.describe Post, type: :model do

  it "投稿内容があれば有効な状態であること" do
    post = Post.new(
      content: "あああ"
    )
    expect(post).to be_valid
  end
end

bundle exec rspecしてみるとテストにが成功することが分かります。

3. モデルの要件を満たさなければ無効であることをテスト

今度はバリデーションが上手く機能しているか確認してみましょう!
contentカラムにはpresence: trueというバリデーションを付与しているので、contentカラムに何も含まれていないとpostインスタンスは無効になるはずです

post_spec.rb
require 'rails_helper'

RSpec.describe Post, type: :model do

  it "投稿内容、ユーザーidがあれば有効な状態であること" do
    post = Post.new(
      content: "あああ"
    )
    expect(post).to be_valid
  end

  it "投稿内容が無ければ無効な状態であること" do
    post = Post.new(
      content: nil
    )
    post.valid?
    expect(post.errors[:content]).to include("can't be blank")
  end
end

今回はインスタンスが無効であると、content属性にエラ〜メッセージが付いてくるという特性を利用して、バリデーションが機能していることをテストしました。

0
0
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
0
0