1
0

More than 3 years have passed since last update.

RSpec&Rails少し複雑なテストのチートシート

Last updated at Posted at 2020-03-06

RSpecでテストカバレッジを上げつつRailsのリファクタリングをしたい場合によく使います。

関数のパラメータをチェック

test.rb
it '#functionにパラメータparamを渡すこと' do
  allow(TargetClass).to receive(:function) {
    |object, param1|

    expect(param1).to eq 'this is parameter'
  }

  TargetClass.function('this is parameter')
end

パラメータが複数ある場合は |object, param1, param2, paramn| のように追加します。
関数の引数の数と一致しなくてもエラーは出ません。

ログのチェック

スタブを使うことで実現できます。
ログレベルはテストしたいログに合わせて設定します。

test.rb
it 'ログが出力される' do
  allow(logger).to receive(:info)

  TargetClass.output_log
  expect(logger).to have_received(:info).with('[INFO] 処理を開始しました')
  expect(logger).to have_received(:info).with('[INFO] 処理を終了しました')
end

参考

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