【Rails】RSpecで忘れがちsubejct, shared_examples, include_context

おつかれさまです

今日はRSpecについてまとめておく。いざ書こうとすると忘れがち

subject

subejctを定義することで、letのように処理をまとめることができる。Dryに書きたい時に使えますね

let(:user) { create(:user) }

subject(:show) do
  get :show, params: { user_id: user.id }; 
end

shared_examples '200を返し、showページがレンダーされること' do
  it { expect { show }.to have_http_status 200 }
  it { expect { show }.to render_template :show }
end

shared_examples

上記でshared_examplesを定義してますが、これもDryで書きたい時に一役なります

使い方はit_behaves_likeの後ろにshared_examplesで定義した文字を入れます

# shared_examplesに定義した事を実行
context 'ユーザータイプがadminの場合' do
  let(:user) { create(:user , type: 'admin') }
  it_behaves_like '200を返し、showページがレンダーされること'
end

include_context

include_contextも共通処理をDryで書きたい時に使える。shared_contextsで定義された共通処理を include する感じ

shared_context 'hogehogesetup' do
  before do
    # 前処理したい事を書く
    end
  end
end

別ファイルでhogehogesetupを呼ぶ

include_context 'hogehogesetup'

ps: テストコードにあまり時間をかけたくないのは、僕だけじゃないはず

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です