Posted By

pmccann on 05/12/07


Tagged

testing


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


Verifier objects


 / Published in: Ruby
 

URL: http://project.ioni.st/post/1211#snippet_1211

Niiice... (stolen from linked site via planetrubyonrails.com)

  1. # Encapsulates some object and executes expressions
  2. # in the context of that object tracking the result
  3. # of the evaluation. As soon as an expression is
  4. # false, the verification fails.
  5. #
  6. # verification = Verifier.new('Marcel') do
  7. # try { size == 6 } # Passes
  8. # try { size == 5 } # Fails
  9. # try { raise } # Doesn't get here
  10. # end
  11. #
  12. # verification.verify
  13. # => false
  14. class Verifier
  15. class FailedVerification < Exception
  16. end
  17.  
  18. class << self
  19. def verify(object, &block)
  20. new(object, &block).verify
  21. end
  22. end
  23.  
  24. attr_reader :object, :results, :block
  25. def initialize(object, &block)
  26. @object = object
  27. @results = []
  28. @verified = false
  29. @block = block
  30. end
  31.  
  32. def verified?
  33. @verified && results.all?
  34. end
  35.  
  36. def verify
  37. instance_eval(&block)
  38. @verified = true
  39. rescue FailedVerification
  40. false
  41. end
  42.  
  43. def try(&block)
  44. results << object.instance_exec(&block)
  45. raise FailedVerification if results.last == false
  46. end
  47. end

Report this snippet  

You need to login to post a comment.