require 'rails_helper' module Mks module Rate RSpec.describe ServiceDeliveryUnitsController, type: :controller do routes { Mks::Rate::Engine.routes } before(:each) do u = create(:user) token = Mks::Auth::TokenAuth.issue(name: u.full_name, email: u.email, id: u.id) request.headers['Authorization'] = "Bearer #{token}" end let(:valid_attributes) { { code: FFaker::Name.unique.name, name: FFaker::Name.name, address: FFaker::Name.name } } let(:invalid_attributes) { { code: nil, name: FFaker::Name.name, address: FFaker::Name.name } } describe 'GET #index' do it 'returns all service delivery units' do 3.times { create(:service_delivery_unit) } get :index data = JSON(response.body) expect(data.count).to eq(3) end end describe 'POST #create' do context 'with valid data' do it 'saves service delivery units' do expect { post :create, params: { service_delivery_unit: valid_attributes }, format: :json }.to change(ServiceDeliveryUnit, :count).by(1) end it 'returns a success message' do post :create, params: { service_delivery_unit: valid_attributes }, format: :json result = JSON(response.body) expect(result['message']).to eq('Service delivery unit saved successfully !') end end context 'with invalid data' do it 'returns error message(s)' do post :create, params: { service_delivery_unit: invalid_attributes }, format: :json result = JSON(response.body) expect(result['code'].count).to be > 0 end end end describe 'PUT #update' do context 'with valid data' do it 'updates service delivery unit' do sdu = create(:service_delivery_unit) put :update, params: { id: sdu.id, service_delivery_unit: { name: 'Service delivery unit 1' } }, format: :json sdu.reload expect(sdu.name).to eq 'Service delivery unit 1' end end context 'with invalid data' do it 'returns an error message' do sdu = create(:service_delivery_unit) put :update, params: { id: sdu.id, service_delivery_unit: { name: nil } }, format: :json result = JSON(response.body) expect(result['name'].count).to be > 0 end end end end end end