summaryrefslogtreecommitdiff
path: root/spec/requests/addresses_controller/update_spec.rb
blob: 0c3662e55b770a9ade3acc8d84f6f953bc2c85a8 (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
47
48
49
50
51
52
53
54
# frozen_string_literal: true

require 'rails_helper'

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

  before(:each) do
    relate_user_and_address(user, address)
  end

  it_behaves_like 'a PUT request' do
    let(:route) { "/api/account/addresses/#{address.id}" }
    let(:wrong_route) { "/api/account/addresses/#{SecureRandom.hex(8)}" }
    let(:expected_error_messages) do
      ["Number can't be blank", "Street can't be blank", "Zip code can't be blank",
       'Country is invalid', "City can't be blank"]
    end
    let(:expected_text) do
      [new_address.number.to_s, new_address.zip_code.to_s, new_address.country, new_address.street,
       new_address.city]
    end
    let(:wrong_params) { { number: '', street: '', zip_code: '', city: '', country: 'Not a country' } }
  end

  context 'when the update params coincide with an already existing address for the user' do
    it 'returns a 422 http status and an error message' do
      new_address.save
      relate_user_and_address(user, new_address)
      put("/api/account/addresses/#{address.id}", params:, headers:)
      expect(response).to have_http_status(422)
      expect(response.body).to include('Ya cuenta con esta dirección')
    end
  end

  context 'when the update params coincide with an already existing address' do
    it 'builds a relationship between the user and the address, without creating another address' do
      new_address.save
      another_user = create(:user_account, role: 'regular')
      relate_user_and_address(another_user, new_address)
      put("/api/account/addresses/#{address.id}", params:, headers:)
      expect(Address.count).to eq(1)
      expect(another_user.addresses.first).to eq(user.addresses.find(new_address.id))
    end
  end
end