ブラックボックステストをRspecで網羅する
はじめに
開発にかけられる時間が限られている場合、詳細なテストまで書くのが辛い場合があります。
(テスト駆動の方が生産性が上がる人もいますが、)
その場合に、最低限httpテストを書けば安心ではないかと思ったのでその時の覚書
今回は成功パターンの事例のみを載せておきます。(主にcontrollerテスト)
index
レスポンスがちゃんと200番で変えってきているか
it 'returns 200' do get :index expect(response).to be_success expect(response).to have_http_status(200) end
show
レスポンスがちゃんと200番で変えってきているか
it 'returns 200' do user = create(:user) get :show, id: user.id expect(response).to be_success expect(response).to have_http_status(200) end
update
渡した引数でちゃんとudpateできているかをチェック
# 何かしらの方法でuserの作成 user = create(:user) it 'change email' do # attributes_forでhashを生成 patch :update, id: user.id, user: attributes_for(:user, email: "hoge@hoge.com") # マッチャで最後に確認 expect(user.reload.email).to rq "hoge@hoge.com" expect(response).to redirect_to "どっかにリダイレクト" end
create
データベースに保存が成功しているかどうか
it 'save success' do expect do post :creaet, :id, user: attributes_for(:user) end.to change(User, :count).by(1) # レコードが増えていることを確認 # リダイレクトされるの302のステータスコードを確認 expect(response).to have_http_status(302) end
最後に
これだけでもやはり、テストがあると安心感いいね!