Created
August 29, 2013 17:07
-
-
Save knowuh/6380764 to your computer and use it in GitHub Desktop.
rspec matcher for checking that a collection is sorted by an attribute
This file contains hidden or 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
RSpec::Matchers.define :be_ordered_by do |attribute| | |
match do |actual| | |
result = true | |
reverse_indicator = "_desc" | |
if attribute =~ /#{reverse_indicator}/ | |
symbol = attribute.gsub(/#{reverse_indicator}/,'').to_sym | |
sorted = actual.sort{ |a,b| b.send(symbol) <=> a.send(symbol)} | |
else | |
sorted = actual.sort{ |a,b| a.updated_at <=> b.updated_at} | |
end | |
sorted.each_with_index do |a,i| | |
result = false unless actual[i] == a | |
end | |
result # return true or false for this matcher. | |
end | |
failure_message_for_should do |actual| | |
"expected that #{actual} would be sorted by #{attribute}" | |
end | |
failure_message_for_should_not do |actual| | |
"expected that #{actual} would not be sorted by #{attribute}" | |
end | |
description do | |
"be a sorted by #{attribute}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment