Help us understand the problem. What is going on with this article?

rspecで404 NotFoundのテストが通らなかった理由

More than 1 year has passed since last update.

404 NotFoundのテストが通らなかった理由

rspecのログを見ると、

レスポンスに404番を返す (FAILED - 1)
Failures:
  1) ProjectsController showアクションを検証する @projectが見つからない場合 レスポンスに404番を返す
     Failure/Error: @project = Project.find(params[:id])

     ActiveRecord::RecordNotFound:
       Couldn't find Project with 'id'=0 [WHERE "projects"."deleted_at" IS NULL]
     # ./app/controllers/projects_controller.rb:38:in `set_project'
     # ./spec/controllers/project_spec.rb:42:in `block (4 levels) in <top (required)>'
Finished in 0.03384 seconds (files took 1.06 seconds to load)
3 examples, 1 failure

となっており、

ActiveRecord::RecordNotFound

というエラーを出されている。

そのため、テストをActiveRecord::RecordNotFoundを返すように書かないといけなかった。

現在は、

expect(response.status).to eq 404

という、HTTPステータスを返すように書いてしまっていた。

そのため、下記のようにActiveRecord::RecordNotFoundを返すように修正すると、テストが通りました。

context '@projectが見つからない場合' do
  it 'レスポンスに404番を返す' do
    expect {
      get :show, params: { id: 0 }
    }.to raise_error(ActiveRecord::RecordNotFound)
  end
end
ProjectsController
  showアクションを検証する
    @projectが存在する場合
      レスポンスに200番を返す
      値をjsonで返す
    @projectが見つからない場合
      レスポンスに404番を返す

Finished in 0.04004 seconds (files took 1.23 seconds to load)
3 examples, 0 failures

showアクションで、存在しないidにアクセスする=get :show, params: { id: 0 }

エラーを出す=raise_error(ActiveRecord::RecordNotFound)

※ActiveRecordに値を渡す時は、{ }ブロックで渡すこと。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした