diff --git a/app/controllers/api/v1/accounts/conversations_controller.rb b/app/controllers/api/v1/accounts/conversations_controller.rb index ec107dfff..10a676738 100644 --- a/app/controllers/api/v1/accounts/conversations_controller.rb +++ b/app/controllers/api/v1/accounts/conversations_controller.rb @@ -142,6 +142,8 @@ class Api::V1::Accounts::ConversationsController < Api::V1::Accounts::BaseContro # and deprecate the support of passing only source_id as the param @contact_inbox ||= ::ContactInbox.find_by!(source_id: params[:source_id]) authorize @contact_inbox.inbox, :show? + rescue ActiveRecord::RecordNotUnique + render json: { error: 'source_id should be unique' }, status: :unprocessable_entity end def build_contact_inbox diff --git a/spec/controllers/api/v1/accounts/conversations_controller_spec.rb b/spec/controllers/api/v1/accounts/conversations_controller_spec.rb index d012d5f53..f38d9c1bf 100644 --- a/spec/controllers/api/v1/accounts/conversations_controller_spec.rb +++ b/spec/controllers/api/v1/accounts/conversations_controller_spec.rb @@ -207,7 +207,7 @@ RSpec.describe 'Conversations API', type: :request do describe 'POST /api/v1/accounts/{account.id}/conversations' do let(:contact) { create(:contact, account: account) } let(:inbox) { create(:inbox, account: account) } - let(:contact_inbox) { create(:contact_inbox, contact: contact, inbox: inbox) } + let!(:contact_inbox) { create(:contact_inbox, contact: contact, inbox: inbox) } context 'when it is an unauthenticated user' do it 'returns unauthorized' do @@ -251,6 +251,16 @@ RSpec.describe 'Conversations API', type: :request do expect(response_data[:additional_attributes]).to eq(additional_attributes) end + it 'does not create a new conversation if source_id is not unique' do + new_contact = create(:contact, account: account) + + post "/api/v1/accounts/#{account.id}/conversations", + headers: agent.create_new_auth_token, + params: { source_id: contact_inbox.source_id, inbox_id: inbox.id, contact_id: new_contact.id }, + as: :json + expect(response).to have_http_status(:unprocessable_entity) + end + it 'creates a conversation in specificed status' do allow(Rails.configuration.dispatcher).to receive(:dispatch) post "/api/v1/accounts/#{account.id}/conversations",