0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【RSpec初学者】モデルのバリデーションテストを書いてみた(Articleモデル編)

Posted at

【RSpec入門】モデルのバリデーションテストを書いてみた(Articleモデル編)

Rails初学者の私が、RSpecでモデルのテストを書いてみました。
今回は、Articleモデルに対して「タイトルと内容が入力されていれば保存できる」というシンプルなテストを実行したときの備忘録です。

事前準備

  • Rails(今回はバージョン6系)
  • RSpec(rspec-rails)をGemfileに追加し、セットアップ済み
  • ArticleモデルとUserモデルがある(ArticleはUserに属する)

テストコード

以下が、実際に書いたテストコードです。

require 'rails_helper'

RSpec.describe Article, type: :model do
  it 'タイトルと内容が入力されていれば、記事を保存できる' do
    user = User.create!({
      email: 'test@example.com',
      password: 'password'
    })

    article = user.articles.build({
      title: Faker::Lorem.characters(number: 10),
      content: Faker::Lorem.characters(number: 300)
    })

    expect(article).to be_valid
  end
end

解説

  • user = User.create!:テスト用のユーザーを作成
  • user.articles.build:そのユーザーに紐づく記事を作成(まだ保存はしていない)
  • Faker:ダミーデータを生成する便利なgem(fakerをインストールしておく必要がある)
  • expect(article).to be_valid:バリデーションエラーがないことを確認。

テストの実行

以下のコマンドでテストを実行する。

bundle exec rspec spec/models/article_spec.rb

実行結果

Finished in 0.07585 seconds (files took 0.97437 seconds to load)
1 example, 0 failures

1つのテストができた。

調べてみた:他の expect の書き方いろいろ

RSpecでは、バリデーション以外にもいろいろな形で expect を使ってテストを書きやすくできるらしい。

値の一致を確認したいとき

expect(article.title).to eq("テストタイトル")

保存されたことを確認したいとき

article.save
expect(article).to be_persisted

エラーになることをテストしたいとき

expect {
  Article.create!(title: "", content: "")
}.to raise_error(ActiveRecord::RecordInvalid)

配列に特定の要素が含まれているか

expect([1, 2, 3]).to include(2)

複数のオブジェクト数を確認したいとき

expect(Article.count).to eq(1)

引き続き、テストについて学んでいきたいと思います。
間違えていたら、すいません。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?