require 'rails_helper' module Mks module Rate RSpec.describe ChargeableServicesController, 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, base_unit_id: create(:unit_of_charge).id, utilization_unit_id: create(:unit_of_charge).id, service_delivery_unit_id: create(:service_delivery_unit).id, service_type_id: create(:service_type).id } } let(:invalid_attributes) { { code: nil, name: FFaker::Name.name, base_unit_id: create(:unit_of_charge).id, utilization_unit_id: create(:unit_of_charge).id, service_delivery_unit_id: create(:service_delivery_unit).id, service_type_id: create(:service_type).id } } describe 'GET #index' do it 'returns all chargeable services' do 3.times { create(:chargeable_service) } get :index data = JSON(response.body) expect(data.count).to eq(3) expect(data[0].count).to eq(11) end end describe 'POST #create' do context 'with valid data' do it 'saves chargeable service' do expect { post :create, params: { chargeable_service: valid_attributes }, format: :json }.to change(ChargeableService, :count).by(1) end it 'returns a success message' do post :create, params: { chargeable_service: valid_attributes }, format: :json result = JSON(response.body) expect(result['message']).to eq('Chargeable service saved successfully !') end end context 'with invalid data' do it 'returns error message(s)' do post :create, params: { chargeable_service: 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 chargeable service ' do cs = create(:chargeable_service) put :update, params: { id: cs.id, chargeable_service: { name: 'Chargeable service 1' } }, format: :json cs.reload expect(cs.name).to eq 'Chargeable service 1' end end context 'with invalid data' do it 'returns an error message' do cs = create(:chargeable_service) put :update, params: { id: cs.id, chargeable_service: { name: nil } }, format: :json result = JSON(response.body) expect(result['name'].count).to be > 0 end end end describe 'GET #sdu_service' do it 'returns services under a given service delivery unit' do sdu1 = create(:service_delivery_unit) sdu2 = create(:service_delivery_unit) 2.times { create(:chargeable_service, service_delivery_unit_id: sdu1.id) } 2.times { create(:chargeable_service, service_delivery_unit_id: sdu2.id) } get :sdu_services, params: { id: sdu1.id }, format: :json data = JSON(response.body) expect(data.count).to eq(2) end end end end end