search_data_manager.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # frozen_string_literal: true
  2. class SearchDataManager
  3. def prepare_test_data
  4. 4.times do |i|
  5. username = "search_test_account_#{i}"
  6. account = Fabricate.create(:account, username: username, indexable: i.even?, discoverable: i.even?, note: "Lover of #{i}.")
  7. 2.times do |j|
  8. Fabricate.create(:status, account: account, text: "#{username}'s #{j} post", visibility: j.even? ? :public : :private)
  9. end
  10. end
  11. 3.times do |i|
  12. Fabricate.create(:tag, name: "search_test_tag_#{i}")
  13. end
  14. end
  15. def indexes
  16. [
  17. AccountsIndex,
  18. PublicStatusesIndex,
  19. StatusesIndex,
  20. TagsIndex,
  21. ]
  22. end
  23. def populate_indexes
  24. indexes.each do |index_class|
  25. index_class.purge!
  26. index_class.import!
  27. end
  28. end
  29. def remove_indexes
  30. indexes.each(&:delete!)
  31. end
  32. def cleanup_test_data
  33. Status.destroy_all
  34. Account.destroy_all
  35. Tag.destroy_all
  36. end
  37. end
  38. RSpec.configure do |config|
  39. config.before :suite do
  40. if search_examples_present?
  41. # Configure chewy to use `urgent` strategy to index documents
  42. Chewy.strategy(:urgent)
  43. # Create search data
  44. search_data_manager.prepare_test_data
  45. end
  46. end
  47. config.after :suite do
  48. if search_examples_present?
  49. # Clean up after search data
  50. search_data_manager.cleanup_test_data
  51. end
  52. end
  53. config.around :each, :search do |example|
  54. search_data_manager.populate_indexes
  55. example.run
  56. search_data_manager.remove_indexes
  57. end
  58. private
  59. def search_data_manager
  60. @search_data_manager ||= SearchDataManager.new
  61. end
  62. def search_examples_present?
  63. RSpec.world.filtered_examples.values.flatten.any? { |example| example.metadata[:search] == true }
  64. end
  65. end