Search code examples
ruby-on-railsrubyrspecrspec-rails

My api is return a :ok when should be returning a :unprocessable_entity


I have an API that I'm currently using rspec to do the tests. In a specific test, I do a patch/put in a unity giving invalid values, but when I do the same test he responds with a status ":ok" and not a ":unprocessable_entity" as they should.

The test:

it "renders a JSON response with errors for the new unit" do
  post units_url,
  params: { unit: invalid_attributes }, headers: valid_headers, as: :json
  expect(response).to have_http_status(:unprocessable_entity)
  expect(response.content_type).to match(a_string_including("application/vnd.api+json"))
end

The update on unit_controller.rb:

def update
  if @unit.update!(unit_params)
    render json: @unit
  else
    render json: @unit.errors, status: :unprocessable_entity
  end
end

The unit_params:

def unit_params
  params.require(:unit).permit(:name)
end

The response:A image where i pass invalid parameters but the system accept them anyway


Solution

  • You need to send such params

    {
      "unit": {
        "name": ""
      }
    }
    

    You don't need update! method because it raises error if validations fail. Use update (without bang) instead