Last active
December 20, 2015 09:59
-
-
Save jimweirich/6112334 to your computer and use it in GitHub Desktop.
Proof of concept for Pre/Post condition assertions based on RSpec/Given
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'given/natural_assertion' | |
require 'given/line_extractor' | |
class Object | |
def self._Gvn_location_of(block) | |
eval "[__FILE__, __LINE__]", block.binding | |
end | |
end | |
module Given | |
AssertionError = Class.new(StandardError) | |
PreconditionError = Class.new(AssertionError) | |
PostconditionError = Class.new(AssertionError) | |
module Assertions | |
def Assert(&block) | |
unless instance_eval(&block) | |
na = Given::NaturalAssertion.new("Assert", block, self, Given::LineExtractor.new) | |
fail AssertionError, na.message | |
end | |
end | |
def Precondition(&block) | |
unless instance_eval(&block) | |
na = Given::NaturalAssertion.new("Precondition", block, self, Given::LineExtractor.new) | |
fail PreconditionError, na.message | |
end | |
end | |
def Postcondition(&block) | |
unless instance_eval(&block) | |
na = Given::NaturalAssertion.new("Postcondition", block, self, Given::LineExtractor.new) | |
fail PostconditionError, na.message | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ruby -Ilib try_precondition.rb | |
/Users/jim/pgm/ruby/given_assertions/lib/given/assertions.rb:26:in `Precondition': Precondition expression failed at try_precondition.rb:10 (Given::PreconditionError) | |
Failing expression: Precondition { n >= 0 } | |
expected: -1 | |
to be greater or equal to: 0 | |
false <- n >= 0 | |
-1 <- n | |
from try_precondition.rb:10:in `sqrt' | |
from try_precondition.rb:19:in `<main>' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'given/assertions' | |
require 'given/fuzzy_number' | |
include Given::Assertions | |
include Given::Fuzzy | |
def sqrt(n) | |
Precondition { n >= 0 } | |
result = Math.sqrt(n) | |
Postcondition { result ** 2 == about(n) } | |
result | |
end | |
sqrt(1) | |
sqrt(2) | |
sqrt(0) | |
sqrt(-1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment