Skip to content

Instantly share code, notes, and snippets.

@nfiniteset
Last active December 28, 2015 08:29
Show Gist options
  • Save nfiniteset/7472267 to your computer and use it in GitHub Desktop.
Save nfiniteset/7472267 to your computer and use it in GitHub Desktop.
A matcher to assert an array is sorted according to the value of the method or key corresponding to a symbol.
# A matcher to assert an array is sorted
# according to the value of the method or key corresponding to a symbol.
#
# Looks like this:
# expect([{ :id => 1 }, {:id => 0}]).to be_ordered_by(:id)
# expect([<User>, <User>]).to be_ordered_by(:id)
RSpec::Matchers.define :be_ordered_by do |sort_method|
match do |actual|
actual = ensure_sendable(actual)
expected_order = actual.sort { |x, y| x.send(sort_method) <=> y.send(sort_method) }
actual == expected_order
end
def ensure_sendable(objects_or_hashes)
objects_or_hashes.map do |obj|
obj.class == Hash ? OpenStruct.new(obj) : obj
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment