summaryrefslogtreecommitdiff
path: root/spec/requests/addresses_controller/create_spec.rb
blob: 5987e0fd52cdf58ffaae75261af8a854ef69789e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe 'POST /account/addresses', type: :request do
  let(:address) { build(:address) }
  let(:user) { create(:user_account, role: 'regular') }
  let(:headers) { { 'Authorization' => "Bearer #{token['token']}" } }
  let(:token) { jwt(user) }
  let(:params) do
    { number: address.number, street: address.street, country: address.country, zip_code: address.zip_code,
      city: address.city }
  end

  it_behaves_like 'a POST request' do
    let(:route) { '/api/account/addresses' }
    let(:expected_error_messages) do
      ["can't be blank", "can't be blank", "can't be blank", 'is invalid', "can't be blank"]
    end
    let(:desired_error_status) { 422 }
    let(:expected_text) { [address.number.to_s, address.zip_code.to_s, address.country, address.street, address.city] }
    let(:wrong_params) { { number: '', street: '', zip_code: '', city: '', country: 'Not a country' } }
  end

  context 'when a similar address already exists in the database' do
    it 'builds a relationship between the user and the address, without creating another address' do
      address.save
      another_user = create(:user_account)
      relate_user_and_address(another_user, address)
      post('/api/account/addresses', params:, headers:)
      expect(Address.count).to eq(1)
      expect(another_user.addresses.first.id).to eq(user.addresses.first.id)
      expect(UserAccountAddress.count).to eq(2)
    end
  end

  context 'when the user alread has the same address' do
    it 'returns a 422 http status and a error message' do
      address.save
      relate_user_and_address(user, address)
      post('/api/account/addresses', params:, headers:)
      expect(response).to have_http_status(422)
      expect(response.body).to include('Ya cuenta con esta dirección')
    end
  end
end