-1
在此示例中,我創建了一個項目,然後發送一個帖子以創建具有相同名稱的另一個項目。因爲它應該會引發ActiveRecord :: RecordNotUnique。我還想檢查它是否返回409 HTTP狀態,但由於它引發了錯誤,它會自動使測試失敗。我如何檢查它是否返回409?RSpec預計HTTP錯誤狀態
require 'rails_helper'
RSpec.describe 'Project Requests', type: :request do
it 'Refuses duplicate projects' do
project_1 = FactoryGirl.create(:project)
post '/projects', name: project_1.name
expect(response.status).to eq(409)
end
end
這裏的RSpec的輸出:
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) already exists.
: INSERT INTO "projects" ("name", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"
下面是我的第二個方法。我期望這個錯誤,那部分工作正常,但我無法檢查狀態,因爲它永遠不會到達那條線。 (注意puts命令怎麼做的RSpec的結果不能輸出任何東西。)
# spec/requests/project_request_spec.rb
require 'rails_helper'
RSpec.describe 'Project Requests', type: :request do
it 'Refuses duplicate projects' do
project_1 = FactoryGirl.create(:project)
expect {
response = post '/projects', name: project_1.name
puts("This code is never executed because the line above fails")
expect(response.status).to eq(409)
}.to raise_error(ActiveRecord::RecordNotUnique)
end
end
這裏是我的RSpec的輸出:
Project Requests
Puts should output text to the console.
Refuses duplicate projects
這會把無論返回什麼錯誤代碼,因此,即使測試通過,它不測試它應該。
我包括響應的原因=是因爲我得到與上面的代碼中的錯誤。 失敗/錯誤:expect(response.status).to eq(409) NoMethodError:未定義方法status爲nil:NilClass – Qaz