assets_matchers.rb 1.5 KB

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