can_csv_import_examples.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. RSpec.shared_examples 'CanCsvImport' do |unique_attributes: []|
  3. describe '.csv_example' do
  4. before do
  5. described_class.destroy_all
  6. end
  7. context 'when no data available' do
  8. it 'still returns the header for the csv example' do
  9. expect(described_class.csv_example).to include('id')
  10. end
  11. end
  12. end
  13. describe '.csv_import' do
  14. let!(:params) { { string: <<~CSV, parse_params: { col_sep: ',' } } }
  15. #{described_class.attribute_names.join(',')}
  16. #{build(factory).attributes.values.join(',')}
  17. CSV
  18. let(:factory) { described_class.name.underscore }
  19. context 'with duplicate entries for unique attributes' do
  20. shared_examples 'case-insensitive duplicates' do |attribute|
  21. let!(:params) { { string: <<~CSV, parse_params: { col_sep: ',' } } }
  22. #{described_class.attribute_names.join(',')}
  23. #{build(factory, attribute => 'Foo').attributes.values.join(',')}
  24. #{build(factory, attribute => 'FOO').attributes.values.join(',')}
  25. CSV
  26. it 'cancels import' do
  27. expect { described_class.csv_import(**params) }
  28. .not_to change(described_class, :count)
  29. end
  30. it 'reports the duplicate' do
  31. expect(described_class.csv_import(**params))
  32. .to include(result: 'failed')
  33. end
  34. end
  35. Array(unique_attributes).each do |attribute|
  36. include_examples 'case-insensitive duplicates', attribute
  37. end
  38. end
  39. context 'when record creation unexpectedly fails' do
  40. around do |example|
  41. described_class.validate { errors.add(:base, 'Unexpected failure!') }
  42. example.run
  43. described_class._validate_callbacks.send(:chain).pop
  44. described_class.send(:set_callbacks, :validate, described_class._validate_callbacks.dup)
  45. end
  46. context 'during a dry-run' do
  47. before { params.merge!(try: 'true') }
  48. it 'reports the failure' do
  49. expect(described_class.csv_import(**params))
  50. .to include(result: 'failed')
  51. end
  52. end
  53. end
  54. end
  55. end