Last active
December 28, 2015 08:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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