about summary refs log tree commit diff
path: root/spec/controllers/concerns/localized_spec.rb
blob: a89e24af04bab0e127eb2ebed8fb95c6df35aaa3 (plain) (blame)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# frozen_string_literal: true

require 'rails_helper'

describe ApplicationController, type: :controller do
  controller do
    include Localized

    def success
      render plain: I18n.locale, status: 200
    end
  end

  before do
    routes.draw { get 'success' => 'anonymous#success' }
  end

  shared_examples 'default locale' do
    it 'sets available and preferred language' do
      request.headers['Accept-Language'] = 'sr-Latn'
      get 'success'
      expect(response.body).to eq 'sr-Latn'
    end

    it 'sets available and preferred language' do
      request.headers['Accept-Language'] = 'ca-ES, fa'
      get 'success'
      expect(response.body).to eq 'ca'
    end

    it 'sets available and compatible language if none of available languages are preferred' do
      request.headers['Accept-Language'] = 'fa-IR'
      get 'success'
      expect(response.body).to eq 'fa'
    end

    it 'sets default locale if none of available languages are compatible' do
      request.headers['Accept-Language'] = ''
      get 'success'
      expect(response.body).to eq 'en'
    end
  end

  context 'user with valid locale has signed in' do
    it "sets user's locale" do
      user = Fabricate(:user, locale: :ca)

      sign_in(user)
      get 'success'

      expect(response.body).to eq 'ca'
    end
  end

  context 'user with invalid locale has signed in' do
    before do
      user = Fabricate.build(:user, locale: :invalid)
      user.save!(validate: false)
      sign_in(user)
    end

    include_examples 'default locale'
  end

  context 'user has not signed in' do
    include_examples 'default locale'
  end
end