1# frozen_string_literal: true
2
3require 'spec_helper'
4
5RSpec.describe CaseSensitivity do
6  describe '.iwhere' do
7    let_it_be(:connection) { Namespace.connection }
8    let_it_be(:model) do
9      Class.new(ActiveRecord::Base) do
10        include CaseSensitivity
11        self.table_name = 'namespaces'
12        self.inheritance_column = :_type_disabled
13      end
14    end
15
16    let_it_be(:model_1) { model.create!(path: 'mOdEl-1', name: 'mOdEl 1', type: Namespaces::UserNamespace.sti_name) }
17    let_it_be(:model_2) { model.create!(path: 'mOdEl-2', name: 'mOdEl 2', type: Group.sti_name) }
18
19    it 'finds a single instance by a single attribute regardless of case' do
20      expect(model.iwhere(path: 'MODEL-1')).to contain_exactly(model_1)
21    end
22
23    it 'finds multiple instances by a single attribute regardless of case' do
24      expect(model.iwhere(path: %w(MODEL-1 model-2))).to contain_exactly(model_1, model_2)
25    end
26
27    it 'finds instances by multiple attributes' do
28      expect(model.iwhere(path: %w(MODEL-1 model-2), name: 'model 1'))
29        .to contain_exactly(model_1)
30    end
31
32    it 'finds instances by custom Arel attributes' do
33      expect(model.iwhere(model.arel_table[:path] => 'MODEL-1')).to contain_exactly(model_1)
34    end
35
36    it 'builds a query using LOWER' do
37      query = model.iwhere(path: %w(MODEL-1 model-2), name: 'model 1').to_sql
38      expected_query = <<~QRY.strip
39      SELECT \"namespaces\".* FROM \"namespaces\" WHERE (LOWER(\"namespaces\".\"path\") IN (LOWER('MODEL-1'), LOWER('model-2'))) AND (LOWER(\"namespaces\".\"name\") = LOWER('model 1'))
40      QRY
41
42      expect(query).to eq(expected_query)
43    end
44  end
45end
46