response
对象响应多个符号类型作为消息。因此,您可以简单地执行以下操作:
expect(response).to be_success
expect(response).to be_error
expect(response).to be_missing
expect(response).to be_redirect
对于其他类型,例如
:created
,您可以创建一个简单的自定义匹配器来包装
assert_response
:
RSpec::Matchers.define :have_status do |type, message = nil|
match do |_response|
assert_response type, message
end
end
expect(response).to have_status(:created)
expect(response).to have_status(404)
这对于已经设置了适当状态的控制器规范来说应该能正常工作。但是,对于功能规范来说,它将无法正常工作。我没有尝试过请求规范,所以在那里您可能会有不同的体验。
之所以可以这样做是因为它利用了RSpec控制器规范背后的类似状态设置。因此,当assert_response
访问@response
时,它是可用的。
这个匹配器可能可以通过简单地复制assert_response
使用的代码来改进:
RSpec::Matchers.define :have_status do |type, message = nil|
match do |response|
if Symbol === type
if [:success, :missing, :redirect, :error].include?(type)
response.send("#{type}?")
else
code = Rack::Utils::SYMBOL_TO_STATUS_CODE[type]
response.response_code == code
end
else
response.response_code == type
end
end
failure_message do |response|
message or
"Expected response to be a <#{type}>, but was <#{response.response_code}>"
end
end
更新: 2014-07-02
现在,使用 RSpec Rails 3 可以直接实现此功能:https://www.relishapp.com/rspec/rspec-rails/v/3-0/docs/matchers/have-http-status-matcher
have_http_status
才包含在其中。RSpec 2中不包括此功能。 - Tinynumbers