Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4615

How do you handle bad requests with RSpec tests in Rails?

$
0
0

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.rbrequire '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  endend

ReviewsController:

# spec/controllers/api/v1/reviews_controller.rbmodule 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  endend

Viewing all articles
Browse latest Browse all 4615

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>