【问题标题】:Rails 4.2 rspec - expect http status to be 201 but is always 200Rails 4.2 rspec - 期望 http 状态为 201 但始终为 200
【发布时间】: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 状态为 201404。在我的 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


【解决方案1】:

您需要先执行请求,然后才能收到状态码。

如果请求尚未执行,response.status_code 将返回 200。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多