Returns an error code when validation fails (#19734)

* Returns an error code when validation fails

Minor fixes

* Adds unit test
This commit is contained in:
Dhurba baral 2023-07-24 17:16:50 +05:45 committed by GitHub
parent 3adeb14ea0
commit 3493c12ad2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 10 deletions

View file

@ -156,11 +156,11 @@ class ArticlesController < ApplicationController
@user = current_user
article = Articles::Creator.call(@user, article_params_json)
render json: if article.persisted?
{ id: article.id, current_state_path: article.decorate.current_state_path }.to_json
else
article.errors.to_json
end
if article.persisted?
render json: { id: article.id, current_state_path: article.decorate.current_state_path }, status: :ok
else
render json: article.errors.to_json, status: :unprocessable_entity
end
end
def update
@ -188,11 +188,11 @@ class ArticlesController < ApplicationController
end
format.json do
render json: if updated.success
@article.to_json(only: [:id], methods: [:current_state_path])
else
@article.errors.to_json
end
if updated.success
render json: @article.to_json(only: [:id], methods: [:current_state_path]), status: :ok
else
render json: @article.errors.to_json, status: :unprocessable_entity
end
end
end
end

View file

@ -196,4 +196,11 @@ RSpec.describe "ArticlesCreate" do
expect(a.published_at).to be_within(1.minute).of(published_at)
end
end
context "when validation error" do
it "returns 422 status code" do
post "/articles", params: { article: { body_markdown: nil } }
expect(response).to have_http_status(:unprocessable_entity)
end
end
end

View file

@ -26,6 +26,15 @@ RSpec.describe "ArticlesUpdate" do
expect(article.reload.title).to eq(new_title)
end
it "returns an unprocessable status with invalid params" do
put "/articles/#{article.id}", params: {
article: { title: "", body_markdown: "Hello World" },
format: :json
}
expect(response).to have_http_status(:unprocessable_entity)
end
it "updates article with front matter params" do
put "/articles/#{article.id}", params: {
article: {