RSpec期望HTTP错误状态

时间:2015-06-18 18:22:03

标签: ruby-on-rails ruby rspec

在这个例子中,我创建了一个项目,然后发送一个帖子来创建另一个具有相同名称的项目。应该如此,它引发了ActiveRecord :: RecordNotUnique。我还想检查它是否返回409 HTTP状态,但由于它引发了错误,它会自动使测试失败。如何检查它是否返回409?

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

无论它返回什么错误代码都会传递,所以即使测试通过,它也不会测试它应该是什么。

1 个答案:

答案 0 :(得分:0)

RSpec已在示例的上下文中为您提供了

response。不要将从post返回的值赋给新的局部变量,只需使用现有方法:

it 'Refuses duplicate projects' do
  project_1 = FactoryGirl.create(:project)
  expect { post '/projects', name: project_1.name }.to raise_error(ActiveRecord::RecordNotUnique)
  expect(response.status).to eq(409)
end