assets_matchers.rb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. RSpec::Matchers.define :include_assets_of do
  3. match do |actual|
  4. expected_array.all? { |elem| find_assets_of(elem, actual) }
  5. end
  6. match_when_negated do |actual|
  7. expected_array.none? { |elem| find_assets_of(elem, actual) }
  8. end
  9. description do
  10. "include assets of #{expected_name}"
  11. end
  12. failure_message do |actual|
  13. list = expected_array.reject { |elem| find_assets_of(elem, actual) }
  14. "Expected hash to include, but not included:\n#{items_for_message(list)}"
  15. end
  16. failure_message_when_negated do |actual|
  17. list = expected_array.select { |elem| find_assets_of(elem, actual) }
  18. "Expected hash to not include, but was included:\n#{items_for_message(list)}"
  19. end
  20. def items_for_message(items)
  21. items
  22. .map { |elem| "- #{item_name(elem)}" }
  23. .join("\n")
  24. end
  25. def expected_name
  26. expected_array
  27. .map { |elem| item_name(elem) }
  28. .join(', ')
  29. end
  30. def item_name(item)
  31. "#{item.class.name}##{item.id}"
  32. end
  33. def expected_array
  34. Array(expected)
  35. end
  36. # Finds corresponding object's data in assets hash
  37. #
  38. # @param [ActiveRecord::Base] object to look for
  39. # @param [Hash] assets hash to use
  40. #
  41. # @example
  42. # assets = Ticket.first.assets
  43. # find_assets_of(Ticket.first, assets)
  44. #
  45. # @return [Hash, nil]
  46. def find_assets_of(object, actual)
  47. actual
  48. .deep_stringify_keys
  49. .dig(object.class.name.gsub(%r{::}, ''), object.id.to_s)
  50. end
  51. end
  52. RSpec::Matchers.define_negated_matcher :not_include_assets_of, :include_assets_of