来自RSpec的意外的status_code

时间:2019-02-13 23:13:22

标签: ruby-on-rails ruby rspec

我正在编写API规范。但是,当响应应为:created时,其返回状态为:unprocessable_entity

announcements_controller

  def update
    head :unprocessable_entity unless announcement
    if annnouncement.update(announcement_params)
      render json: annoucement, status: :ok
    else
      render_unprocessable_entity
    end
  end

  def announcement
    Announcement.find(params[id])
  end

announcements_controller_spec

it 'fails when announcement does not exists' do
  data = {
    id: 999_999,
    announcement: {
      body: ''
    }
  }.to_json
  post "/api/announcements/#{property.slug}", params: data, headers: headers
  expect(response).to have_http_status(:unprocessable_entity)
end

故障响应

  1) Api::AnnouncementsController#update fails when announcement does not exists
     Failure/Error: expect(response).to have_http_status(:unprocessable_entity)
       expected the response to have status code :unprocessable_entity (422) but it was :created (201)

1 个答案:

答案 0 :(得分:3)

您使用post而不是put。因此,您可以根据需要将请求路由到#create的{​​{1}}控制器操作中。

您写的是:

#update

缺少一个冒号:

Announcement.find(params[id])