Jan 21 RSpec simple matcher to specify an array should be sorted
tags:
RSpec is a lot about readability. And its matchers are really a joy to aid you on that. And now it is even easier to add simple matchers for (in David’s own words) you to create your own custom matchers in just a few lines of code when you don’t need all the power of a completely custom matcher object.
Let’s say you want to spec your array is sorted by an attribute on the contained elements, like:
#in your *_spec.rb it 'should be sorted incrementally' do struct_array.should be_sorted_by(:attr) end
Simple, define a simple matcher and make sure you include in your spec_helper.rb.The trick is the simple matcher returns a boolean that will make expectation pass (returning true of course) or not.
def be_sorted_by(attr)
simple_matcher("a sorted fixnum array") do |given|
ary = given.collect { |e| e.send(attr).to_i }
ary.sort == ary
end
end
yes, you noticed correctly the to_i in the matcher implementation, well I’ll leave it to you to extend that :-)