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

Last updated at Posted at 2025-10-07

自分メモ

事前に生成したいものはlet!before doで準備する。
let!before doletの優先順位で上から実行される。

# 「guest」という名前のUserインスタンスを作成
let!(:guest) { create(:user) }

# 「client」という名前のClientインスタンスを作成 ※user_idはguestと同じもの
let!(:client) { create(:client, user: guest) }

# 以降のテストで「guest」がclientロールを持つことを知らず「guest」を使う場面でエラーになってしまった
# そのために、reloadして最新のDB情報を知らせる
# しかし、「guest.reload」をそのまま書くと、テスト実行時ではなくコードが読み込まれた時に実行となり、エラーとなるのでbeforeで囲む
before do
 guest.reload
end 

Rspecで定義するための種類

  • ヘルパーメソッド
    • let!
      • テスト実行前に必ず生成(beforeよりの先に実行)
    • let
      • 必要になった時、初めて生成(遅延評価)
  • フック
    • before do ... end
      • テストの直前に実行
    • after do ... end
      • テストが直後に実行
        • 通知など外部API連携するものはモックで作ることが多いので、テストで作ったファイルや一時データを削除するなど内部で後処理したいケースに使える
    • around do |example| ... example.run ... end
      • テストの前後で必ず何かしたい時に使う
        • 通常のDB保存はMVCの流れで実行されるがわざとロールバックさせたい時など
around do |example|
 ActiveRecord::Base.transaction do
   example.run
   raise ActiveReacord::Rollback
 end
end
around do |exapmple|
 Rails.logger.info "テスト開始"
 example.run
 Rails.logger.info "テスト終了"
end

it "Aのテスト" do
  # ここがexample.runで実行される
end

it "Bのテスト" do
  # ここがexample.runで実行される
end
  • exampleexample.runはお決まりのセット(慣習的に使われる)
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?