【发布时间】:2016-08-26 09:29:26
【问题描述】:
我有以下创建方法。
def create
User.transaction do
@u = User.create(user_params)
@u.create_role!(account_params)
@u.create_address!(address_params)
end
if params.has_key?("manager_id") then
if Manager.exists?(params["sam_id"]) then
@u.update(manager_id: params["manager_id"])
else
raise ActiveRecord::RecordNotFound, "The Mananger with id #{params["manager_id"]} does not exist"
end
end
res = @u.attributes.except("created_at","updated_at").merge(
@u.address.attributes.except("updated_at","created_at")
){|key,v1,v2|v1}
render json: res.to_json, status: :created
end
如果不满足角色和地址的某些验证,则返回的 http 状态为 201 或 404。在我的 rspec 测试中,我使用
it "returns status - 201 " do
expect(response).to have_http_status(201)
end
但我总是收到这个失败消息
12) Api::V1::UserController POST #create Success returns status - 201
Failure/Error: expect(response).to have_http_status(201)
expected the response to have status code 201 but it was 200
# ./spec/controllers/api/v1/user_controller_spec.rb:126:in `block (4 levels) in <top (required)>'
POST 请求的其他测试通过。例如,刚刚创建的用户的返回模式的匹配器运行成功。我不明白为什么我的测试总是返回 200 ok 而不是 201
【问题讨论】:
-
你在服务器控制台中得到了什么?
-
Curl 效果很好。我得到
Completed 201 Created in 226ms (Views: 0.1ms | ActiveRecord: 19.5ms) -
您是否尝试过以这种方式期待
expect(response).to have_http_status(:created)? -
为什么在请求不正确的情况下使用404 Not Found?也许 400 Bad Request 会更好
-
是的,这是真的:)
标签: ruby-on-rails ruby-on-rails-4 rspec