Home > database >  How can i validate some attributes?
How can i validate some attributes?

Time:11-22

How can i validate if params have 'name' and 'section'? for example: i want to validate 'name' but if there is not then i have to return 400, same with 'section'

 context 'validation' do
        let!(:params) do
          { article: {
            name: 'a1',
            section: 'A'
            ...
            color: 'red'
          } }
        end

i dont know how can i compare

it 'test, not allow empty name' do
   expect(name eq '').to have_http_status(400)
end

CodePudding user response:

While you could check the parameters directly:

def create
  if params[:article][:name].blank? || params[:article][:section].blank? 
     return head 400
  end 
 
  # ...
end

The Rails way of performing validation is through models:

class Article < ApplicationRecord
  validates :name, :section, presence: true
end
class ArticlesController < ApplicationController
 
  # POST /articles
  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article, status: :created
    else
      # Yes 422 - not 400
      render :new, status: :unprocessable_entity
    end
  end

  private
 
  def article_params
    params.require(:article)
          .permit(:name, :section, :color)
  end
end
require 'rails_helper'
RSpec.describe "Articles API", type: :request do
  describe "POST /articles" do
    context "with invalid parameters" do
      it "returns 422 - Unprocessable entity" do
        post '/articles',
          params: { article: { name: '' }} 
        expect(response).to have_http_status :unproccessable_entity 
      end
    end
  end
end

This encapsulates the data together with validations that act on the data and validation errors so that you display it back to the user.

Models (or form objects) can even be used when the data isn't saved in the database.

  • Related