Shoulda matchers - Rspec - Test controllers Actions to Json Response - FastJSON

244 views Asked by At

How to test using shoulda-matchers for these actions, to response JSON success 200, and fail 422 and how to test with normal RSpec: both cases if you can:

I think there is missing some information for shoulda matches on its repository. if you can help thanks very much.

  module V1
    class MeasurementsController < ApplicationController
      protect_from_forgery with: :null_session
      before_action :set_measurement, only: %i[destroy]

      def index
        measurement = Measurement.all

        render json: MeasurementSerializer.new(measurement).serialized_json
      end

      def create
        measurement = Measurement.new(measurement_params)

        if measurement.save
          render json: MeasurementSerializer.new(measurement).serialized_json
        else
          render json: { error: measurement.errors.messages }, status: 422
        end
      end

      def destroy
        if @measurement.destroy
          head :no_content
        else
          render json: { error: measurement.errors.messages }, status: 422
        end
      end

      private

      def set_measurement
        @measurement = Measurement.find(params[:id])
      end

      def measurement_params
        params.require(:measurement).permit(:time, :date, :sport_id)
      end
    end
  end
end```
2

There are 2 answers

0
Samuel-Zacharie Faure On

No need for shoulda-matchers You can test with something like this:

require 'rails_helper'

describe V1::MeasurementsController do
  describe '#index', type: request do
    it 'respond with 200' do
      get /your/endpoint

      expect(response).to have_http_status(200)
    end
  end
end

0
Gonza On

what works for me

describe 'GET #index' do
    before { get :index }

    it { should respond_with(200) }
  end