Skip to content

Instantly share code, notes, and snippets.

@seako
Created November 24, 2013 21:46
Show Gist options
  • Save seako/7632799 to your computer and use it in GitHub Desktop.
Save seako/7632799 to your computer and use it in GitHub Desktop.
RSpec::Matchers.define :be_an_ordering_of do |all_records, condition|
match do |ordered_records|
should_be_an_ordering(all_records, ordered_records, &condition)
end
end
def should_be_an_ordering(all_records, ordered_records, &condition)
flunk "There are no records" if all_records.empty?
flunk "Your ordered records are the same as the default ordering" if all_records == ordered_records
records_ordered_by_condition = all_records.sort(&condition)
flunk "Your ordering returns too few records" if ordered_records.length < all_records.length
flunk "Your ordering returns too many records" if ordered_records.length > all_records.length
ordered_records.map(&:id).should == records_ordered_by_condition.map(&:id)
end
@seako
Copy link
Author

seako commented Nov 24, 2013

an alternate version using sort_by that handles the case where at least one record is equal to another

def should_be_an_ordering(all_records, ordered_records, &condition)                                                                                                                                        
  flunk "There are no records" if all_records.empty?                                                                                                                                                       
  flunk "Your ordering returns too few records" if ordered_records.length < all_records.length                                                                                                             
  flunk "Your ordering returns too many records" if ordered_records.length > all_records.length                                                                                                            

  records_ordered_by_condition = all_records.sort_by(&condition)                                                                                                                                           

  warn "Your ordered records are the same as the default ordering" if all_records.map(&condition) == ordered_records.map(&condition)                                                                       
  warn "Ordering by your condition did not change ordering" if all_records.map(&condition) == records_ordered_by_condition.map(&condition)                                                                 

  records_ordered_by_condition.map(&condition).should == ordered_records.map(&condition)                                                                                                                   
end 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment