1f4dlw
Last Updated: February 25, 2016
·
1.109K
· benburton

Testing ordering with each_cons

This is based on a bit of interesting code I observed the other day. In Ruby, the each_cons Array method allows you execute a block on an array of n-consecutive elements. For example:

 > (1..10).each_cons(2) {|a| p a}
[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]
[8, 9]
[9, 10]
 => nil 

This is especially handy if you want to test sorting. Suppose we have the following ActiveRecord::Base subclass:

class BlogPost < ActiveRecord::Base
  attr_accessible :title
  scope :by_title, order('title ASC')
end

In order to test that our :by_title scope sorts correctly, we can check that the first element in every each_cons is less than or equal to the second:

describe BlogPost do
  before {
    BlogPost.create(title: 'Blog Post A')
    BlogPost.create(title: 'Blog Post B')
    BlogPost.create(title: 'Blog Post C')
  }
  describe ".by_title" do
    subject { BlogPost.by_title }
    it "should return ordered blog posts" do
      subject.each_cons(2) do |a, b|
        a.title.should be <= b.title
      end
    end
  end
end

Nothing Earth-shattering, but I thought it was pretty neat.