1
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初学者】contextを使ってテストを読みやすく整理する

Posted at

【RSpec入門】contextを使ってテストを読みやすく整理する

RailsでRSpecのモデルテストを書いていて、contextという便利な構文を知りました。
これは「どういう前提条件のもとでテストを行うのか?」を整理して表現するためのものらしいです。

今回は、実際にArticleモデルのテストでcontextを使ってみたので、その内容をまとめてみました。

書いたテストコード

require 'rails_helper'

RSpec.describe Article, type: :model do
  context 'タイトルと内容が入力されている場合' do
    before 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)
      })
    end

    it '記事を保存できる' do
      expect(@article).to be_valid
    end
  end
end

そもそもcontextとは?

  • context は「前提条件(= テストする状況)」をグループ分けする。
  • 今回、「タイトルと内容が入力されている場合」という条件を指定してみた。
  • contextの中に複数のit(テスト内容)を書くことができ、条件ごとにまとめられる。

beforeブロックについて

  • before do ... end の中に、各テストの前に毎回実行したい処理を記載。
  • 今回は、ユーザーと記事のセットアップをここにまとめていく。
  • @article というインスタンス変数にしておくことで、itブロックの中でも使える。

実行コマンド

ターミナルで以下のコマンドを実行

bundle exec rspec spec/models/article_spec.rb

実行結果

Finished in 0.07647 seconds (files took 1.12 seconds to load)
1 example, 0 failures

成功しました

わかったこと

  • context を使うことで、テストの構造が見やすくなり、条件ごとの整理がしやすくなる
  • 共通のセットアップ処理は before ブロックにまとめると便利

読んでいただきありがとうございます。
初学者のため、間違えていたらすいません

1
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
1
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?