|
| 1 | +require "rails_helper" |
| 2 | + |
| 3 | +describe ActiveAdminAddons::EnumUtils do |
| 4 | + let(:model_name) { 'SomeModel' } |
| 5 | + let(:model_class) { model_name.constantize } |
| 6 | + let(:enum_translations) { { value1: 'value 1 translation', value2: 'value 2 translation' } } |
| 7 | + let(:generic_model) do |
| 8 | + Class.new(ActiveRecord::Base) do # rubocop:disable Rails/ApplicationRecord |
| 9 | + enum some_enum: { value1: 0, value2: 1 } |
| 10 | + end |
| 11 | + end |
| 12 | + |
| 13 | + def translation_key(enum_option_to_translate) |
| 14 | + "activerecord.attributes.some_model.some_enums.#{enum_option_to_translate}" |
| 15 | + end |
| 16 | + |
| 17 | + before do |
| 18 | + stub_const(model_name, generic_model) |
| 19 | + enum_translations.each do |enum_option_name, enum_translation| |
| 20 | + allow(I18n).to receive(:t).with( |
| 21 | + translation_key(enum_option_name), default: enum_option_name.to_s |
| 22 | + ).and_return(enum_translation) |
| 23 | + end |
| 24 | + end |
| 25 | + |
| 26 | + describe '#options_for_select' do |
| 27 | + context 'using enum option name as value' do |
| 28 | + let(:expected_options) do |
| 29 | + enum_translations.map do |enum_option_name, enum_translation| |
| 30 | + [enum_translation, enum_option_name.to_s] |
| 31 | + end |
| 32 | + end |
| 33 | + |
| 34 | + it 'returns correct array of translations and enum option names' do |
| 35 | + options = described_class.options_for_select(model_class, 'some_enum') |
| 36 | + expect(options).to match_array(expected_options) |
| 37 | + end |
| 38 | + end |
| 39 | + |
| 40 | + context 'using db value' do |
| 41 | + let(:expected_options) do |
| 42 | + enum_translations.map do |enum_option_name, enum_translation| |
| 43 | + [enum_translation, generic_model.some_enums[enum_option_name]] |
| 44 | + end |
| 45 | + end |
| 46 | + |
| 47 | + it 'returns correct array of translations and enum db values' do |
| 48 | + options = described_class.options_for_select(model_class, 'some_enum', use_db_value: true) |
| 49 | + expect(options).to match_array(expected_options) |
| 50 | + end |
| 51 | + end |
| 52 | + end |
| 53 | + |
| 54 | + describe '#translate_enum_option' do |
| 55 | + let(:enum_option_to_translate) { 'value1' } |
| 56 | + |
| 57 | + it 'returns correct translation' do |
| 58 | + translation = described_class.translate_enum_option( |
| 59 | + model_class, 'some_enum', enum_option_to_translate |
| 60 | + ) |
| 61 | + expect(translation).to eq(enum_translations[enum_option_to_translate.to_sym]) |
| 62 | + end |
| 63 | + end |
| 64 | +end |
0 commit comments