can_csv_import_examples.rb 1.8 KB

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