Math Operators in English

Tagged with rspec

Language: Ruby

By putting this code in a Rails initializer, it will give you access to the <, <=, >=, > operators in your Rspec tests. It allows you to write tests like:

@event.date.should be_before(Date.today) @cart.discount.should be_less_than_or_equal_to(10)

View as text

# These are helper methods for running rspec tests that give english names to mathematical operators
module MathOperatorHelpers
  def less_than?(other)
    self < other
  end
  
  def less_than_or_equal_to?(other)
    self <= other
  end
  
  def greater_than?(other)
    self > other
  end
  
  def greater_than_or_equal_to?(other)
    self >= other
  end
  
  def between?(first, second)
    first <= self && self <= second
  end
  
  alias_method :before?, :less_than?
  alias_method :before_or_on?, :less_than_or_equal_to?
  alias_method :after?, :greater_than?
  alias_method :after_or_on?, :greater_than_or_equal_to?
end

%w(Integer Float Date DateTime Time).each do |class_name|
  eval <<-EOS
    class #{class_name}
      include MathOperatorHelpers
    end
  EOS
end
Original snippet written by Mike Weber
Last updated at 15:37 PM on Oct 10, 2008

SnippetStash costs money to host and develop. The service is free for everyone to use
but if you found it useful please consider making a small donation.