require 'rails_helper' module Logistics module Core RSpec.describe UnitsController, type: :controller do routes { Logistics::Core::Engine.routes } let(:valid_attributes) { { abbreviation: FFaker::Name.name, name: FFaker::Name.name, unit_type_id: create(:unit_type).id, rate_to_base: 1 } } let(:invalid_attributes) { { abbreviation: FFaker::Name.name, name: '', unit_type_id: create(:unit_type).id, rate_to_base: 1 } } describe "GET #index" do it "assigns all units as @units" do u = create(:unit) get :index, format: :json result = JSON(response.body) expect(result['data'][0]['abbreviation']).to eq u.abbreviation expect(result['data'][0]['name']).to eq u.name expect(result['data'][0]['unit_type_id']).to eq u.unit_type_id expect(result['data'][0]['unit_type_name']).to eq u.unit_type.name end end describe "POST #create" do context "with valid params" do it "creates a new unit" do expect { post :create, params: { :unit => valid_attributes }, format: :json }.to change(Unit, :count).by(1) end it "should return a success message" do post :create, params: { :unit => valid_attributes }, format: :json result = JSON(response.body) expect(result['message']).to eq('Unit saved successfully!') end end context "with invalid params" do it 'should return an error message' do post :create, params: { :unit => invalid_attributes }, format: :json result = JSON(response.body) expect(result['errors']).to include("Unit Name can't be blank") end end end describe "PUT #update" do context "with valid params" do let(:new_attributes) { { name: FFaker::Name.name } } it "updates the requested unit" do unit = create(:unit) old_data = unit.name put :update, params: { :id => unit.to_param, :unit => new_attributes }, format: :json unit.reload expect(unit.name).not_to eq old_data end it "should return a success message" do unit = create(:unit) put :update, params: { :id => unit.to_param, :unit => valid_attributes }, format: :json result = JSON(response.body) expect(result['message']).to eq('Unit updated successfully!') end end context "with invalid params" do it "should return an error message" do unit = create(:unit) put :update, params: { :id => unit.to_param, :unit => invalid_attributes }, format: :json result = JSON(response.body) expect(result['errors']).to include("Unit Name can't be blank") end end end end end end