コピペコードで快適生活

明日使えるソースを自分のために

RSpecのletの使い方 - before&インスタンス変数使うやり方との比較

ずっとbefore&インスタンス変数でやってたので、let使うやり方をメモしておく。

require 'spec_helper'

describe 'beforeとletの違いについて' do
  context 'インスタンス変数を使う場合' do
    before do
      @account = create(:account)
    end

    it 'アカウントが存在する' do
      db_account = Account.find_by(account_id: @account.id)
      expect(db_account.present?).to eq true
    end
  end

  context 'letを使う場合' do
    # beforeと同じタイミングで、accountメソッドが作られる
    # 呼ばれたときに初期化されて、以降は同じインスタンスを返す
    let(:account) { create(:account) }

    context '一度も参照しない場合' do
      it 'アカウントは存在しない' do
        expect(Account.count).to eq 0
      end
    end

    context '一度でも参照した場合' do
      it 'アカウントは存在する' do
        db_account = Account.find_by(account_id: account.id)
        expect(db_account.present?).to eq true
        expect(Account.count).to eq 1
      end
    end
  end

  context 'let!を使う場合' do
    # 定義と同時に初期化される
    let!(:account) { create(:account) }

    context '一度も参照しない場合' do
      it 'アカウントは存在する' do
        expect(Account.count).to eq 1
      end
    end
  end
end

※参考にさせていただきました
RSpecのletを使うのはどんなときか?(翻訳) - Qiita