In my test database, I have reviews that i am making API calls to in my API-only Rails 5 app.
So far i have written tests for my index and show actions for the ReviewsController.
How do i handle error/bad request handling? For instance, if someone tries to go to a route that doesn't exist or if someone tries to navigate to a show route without an existing id, how is that done in RSpec?
# spec/controllers/api/v1/reviews_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V1::ReviewsController do
describe "GET #index" do
before do
get :index
end
it "returns HTTP Success" do
expect(response).to have_http_status(:success)
end
it "JSON body response contains expected review attributes" do
json_response = JSON.parse(response.body)
json_response["status"].should == "SUCCESS"
end
end
describe "GET #show" do
before do
get :show, params: { id: 1 }
end
it "returns HTTP Success" do
expect(response).to have_http_status(:success)
end
it "JSON body response contains expected review attributes" do
json_response = JSON.parse(response.body)
json_response["status"].should == "SUCCESS"
end
end
end
ReviewsController:
# spec/controllers/api/v1/reviews_controller.rb
module Api
module V1
class ReviewsController < ApplicationController
def index
@reviews = Review.order(created_at: :desc)
render json: { status: 'SUCCESS', message: 'loaded reviews', data: @reviews }
end
def show
@review = Review.find(params[:id])
render json: { status: 'SUCCESS', message: 'loaded the review', data: @review }
end
private
def review_params
params.require(:review).permit(:title, :star, :content, :name, :date)
end
end
end
end
Aucun commentaire:
Enregistrer un commentaire