search_spec.rb 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. require 'rails_helper'
  3. RSpec.describe Service::ExternalDataSource::Search do
  4. describe '#execute', db_adapter: :postgresql do
  5. context 'with ElasticSearch', searchindex: true do
  6. let(:attribute) do
  7. create(:object_manager_attribute_autocompletion_ajax_external_data_source, :elastic_search)
  8. end
  9. let(:searchterm) { SecureRandom.uuid }
  10. let(:user1) { create(:agent, firstname: searchterm) }
  11. let(:user2) { create(:agent, firstname: searchterm) }
  12. before do
  13. user1
  14. user2
  15. searchindex_model_reload([User])
  16. end
  17. it 'returns search results' do
  18. json = described_class.new.execute(attribute: attribute, render_context: {}, term: searchterm)
  19. expect(json).to eq([
  20. { value: user1.id.to_s, label: user1.email },
  21. { value: user2.id.to_s, label: user2.email }
  22. ])
  23. end
  24. end
  25. context 'with mocked response' do
  26. let(:instance) { described_class.new }
  27. let(:json_response) do
  28. {
  29. 'deadend' => 'yes',
  30. 'results' => {
  31. 'items' => [
  32. { 'data' => { 'id' => 1, 'name' => 'name 1' } },
  33. { 'data' => { 'id' => 2, 'name' => 'name 2' } },
  34. { 'data' => { 'id' => 3, 'name' => false } },
  35. { 'data' => { 'id' => 4, 'name' => true } },
  36. ]
  37. }
  38. }
  39. end
  40. let(:list_key) { 'results.items' }
  41. let(:value_key) { 'data.id' }
  42. let(:label_key) { 'data.name' }
  43. let(:attribute) do
  44. create(:object_manager_attribute_autocompletion_ajax_external_data_source,
  45. list_key: list_key,
  46. value_key: value_key,
  47. label_key: label_key)
  48. end
  49. before do
  50. allow_any_instance_of(ExternalDataSource)
  51. .to receive(:fetch_json)
  52. .and_return(json_response)
  53. end
  54. it 'returns correct data' do
  55. json = instance.execute(attribute: attribute, render_context: {}, term: 'term')
  56. expect(json).to eq([
  57. { value: 1, label: 'name 1' },
  58. { value: 2, label: 'name 2' },
  59. { value: 3, label: false },
  60. { value: 4, label: true },
  61. ])
  62. end
  63. context 'when parsing fails' do
  64. let(:list_key) { 'deadend' }
  65. it 'raises error' do
  66. expect { instance.execute(attribute: attribute, render_context: {}, term: 'term') }
  67. .to raise_error(Exceptions::UnprocessableEntity)
  68. end
  69. end
  70. end
  71. end
  72. end