LoginSignup
11
3

More than 1 year has passed since last update.

RSpecでlet_it_beを使って、作成されるレコード数を減らす

Last updated at Posted at 2020-04-23

let_it_beを使うと作成されるレコード数を減らすことができる

解説

こういうbooksテーブルがあるとする

create_table "books", force: :cascade do |t|
  t.string "title"
  t.string "description"
  t.datetime "created_at", precision: 6, null: false
  t.datetime "updated_at", precision: 6, null: false
end

factoryを用意します

FactoryBot.define do
  factory :book do
    title { 'hoge' }
    description { 'fuga' }
  end
end

こんな感じのテストがあるとします

RSpec.describe do
  describe 'Book' do
    let!(:book) { create(:book) }
    it 'test 1' do
      expect(book.title).to eq('hoge')
      expect(Book.count).to eq(1)
    end

    it 'test 2' do
      expect(book.title).to eq('hoge')
      expect(Book.count).to eq(1)
    end

    it 'test 3' do
      expect(book.title).to eq('hoge')
      expect(Book.count).to eq(1)
    end
  end
end

上のテストを実行することで、計3回レコードが生成されます

検証のため、
Bookモデルにafter_saveコールバックを設定してテストを走らせてみます

class Book < ApplicationRecord
  after_save :check_create

  private

  def check_create
    p 'created!'
  end
end

コールバックが3回呼ばれています
スクリーンショット 2020-04-24 0.40.42.png

レコード生成回数を減らしたい!

let_it_beという存在を知りました
gemのリポジトリ

セットアップ

gem 'test-prof' をGemfileに追加し、bundle install

rails_helper.rbrequire 'test_prof/recipes/rspec/let_it_be'を追加

先ほどのテストファイルで

let!(:book) { create(:book) }

let!

let_it_be(:book) { create(:book) }

let_it_beに変えるだけ

これでテスト走らせてみると、1度しかコールバック呼ばれていない

スクリーンショット 2020-04-24 0.47.04.png

所感

テストが遅くならないようちりつもでやっていきたいと思いました

以上です。
読んでいただき、ありがとうございます。

11
3
2

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
11
3