class RSpecApi::Matchers::Sort::Matcher

Attributes

field[RW]
verse[RW]

Public Class Methods

new(options = {}) click to toggle source
# File lib/rspec-api/matchers/sort/matcher.rb, line 9
def initialize(options = {})
  @field = options[:by]
  @verse = options[:verse]
end

Public Instance Methods

description() click to toggle source
# File lib/rspec-api/matchers/sort/matcher.rb, line 18
def description
  if field
    %Q(be sorted by #{reverse? ? 'descending' : 'ascending'} #{field})
  else
    %Q(be sorted)
  end
end
matches?(response) click to toggle source
# File lib/rspec-api/matchers/sort/matcher.rb, line 14
def matches?(response)
  super && all_objects_have_field? && has_two_objects? && is_sorted?
end

Private Instance Methods

all_objects_have_field?() click to toggle source
# File lib/rspec-api/matchers/sort/matcher.rb, line 28
def all_objects_have_field?
  if field
    json.all?{|item| item.is_a?(Hash) && item.key?(field)}
  else
    true
  end
end
has_two_objects?() click to toggle source
# File lib/rspec-api/matchers/sort/matcher.rb, line 36
def has_two_objects?
  if json.length < 2
    msg = "Cannot test sorting on an array with #{json.length} items"
    raise RSpec::Core::Pending::PendingDeclaredInExample.new msg
  else
    true
  end
end
is_sorted?() click to toggle source
# File lib/rspec-api/matchers/sort/matcher.rb, line 45
def is_sorted?
  values = json.map{|item| item[field]}
  values.sort == (reverse? ? values.reverse : values)
end
reverse?() click to toggle source
# File lib/rspec-api/matchers/sort/matcher.rb, line 50
def reverse?
  ['desc', 'descending'].include? verse.to_s
end