ruby on rails - RSpec expect HTTP error status -
in example, create project, send post create project same name. should, raises activerecord::recordnotunique. want check returns 409 http status, since raises error, automatically fails test. how can check returns 409?
require 'rails_helper' rspec.describe 'project requests', type: :request 'refuses duplicate projects' project_1 = factorygirl.create(:project) post '/projects', name: project_1.name expect(response.status).to eq(409) end end
here's rspec output:
failures: 1) project requests refuses duplicate projects failure/error: post '/projects', name: project_1.name activerecord::recordnotunique: pg::uniqueviolation: error: duplicate key value violates unique constraint "index_projects_on_name" detail: key (name)=(dr. brain) exists. : insert "projects" ("name", "created_at", "updated_at") values ($1, $2, $3) returning "id"
below second approach. expect error, , part works fine, can't check status because never gets line. (notice how puts command doesn't output in rspec results.)
# spec/requests/project_request_spec.rb require 'rails_helper' rspec.describe 'project requests', type: :request 'refuses duplicate projects' project_1 = factorygirl.create(:project) expect { response = post '/projects', name: project_1.name puts("this code never executed because line above fails") expect(response.status).to eq(409) }.to raise_error(activerecord::recordnotunique) end end
here's rspec output:
project requests puts should output text console. refuses duplicate projects
that pass no matter error code returns, though test passes, doesn't test it's supposed to.
response
provided rspec in context of example. rather assign value returned post
new local variable, use existing method:
it 'refuses duplicate projects' project_1 = factorygirl.create(:project) expect { post '/projects', name: project_1.name }.to raise_error(activerecord::recordnotunique) expect(response.status).to eq(409) end
Comments
Post a Comment