21

I want to use the assertions and put valuidations in my ruby code (e.g: checking if a zip file is created, label is present, message in the text area, etc). I have put a few assert statements like assert @selenium.is_text_present(textMessage), but they don't work.

Please let me know if any ruby gem for assertions is to be installed.

P Shved
  • 96,026
  • 17
  • 121
  • 165
Harry
  • 211
  • 1
  • 2
  • 3
  • 2
    Please, make sure you've read the [formatting guide](http://stackoverflow.com/editing-help), notice that we all are always friendly, and that's why we skip usual "hi/thanks" parts of the messages, and--welcome to StackOverflow! – P Shved Jul 16 '10 at 11:23
  • Think this is similar - http://stackoverflow.com/questions/147969/is-it-idiomatic-ruby-to-add-an-assert-method-to-rubys-kernel-class – carrutherji Jul 16 '10 at 11:31

3 Answers3

32

For simple asserts, you're probably best off rolling your own assert method taking a block:

ruby-1.9.1-p378 > class AssertionError < RuntimeError
ruby-1.9.1-p378 ?>  end
 => nil 
ruby-1.9.1-p378 > def assert &block
ruby-1.9.1-p378 ?>  raise AssertionError unless yield
ruby-1.9.1-p378 ?>  end
 => nil 
ruby-1.9.1-p378 > assert { 1 > 0 }
 => nil 
ruby-1.9.1-p378 > assert { 5 == 12 }
AssertionError: AssertionError
    from (irb):8:in `assert'
    from (irb):11
    from /Users/mr/.rvm/rubies/ruby-1.9.1-p378/bin/irb:17:in `<main>'

In copypastastable form:

class AssertionError < RuntimeError
end

def assert &block
    raise AssertionError unless yield
end

i = 1
assert {i >= 0}
assert { 5 == 12 }
Bulwersator
  • 1,102
  • 2
  • 12
  • 30
Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • 2
    Is there a reason for using a block as an argument instead of a simple boolean? – Khaja Minhajuddin May 26 '15 at 21:50
  • 5
    If the assert method checks some other condition (e.g. 'if DEBUG_ENABLED') before doing the "raise... unless yield", then if that condition returns false, the yield won't ever be invoked, and hence the passed-in block won't ever be evaluated. If what the block does is expensive, this could have a big effect on program execution time. – Some Guy Mar 09 '16 at 12:56
5

Use the solid_assert gem to add assertions to Ruby.

See:
solid_assert: A simple Ruby assertion utility
Is it idiomatic Ruby to add an assert( ) method to Ruby's Kernel class?

Community
  • 1
  • 1
Yarin
  • 173,523
  • 149
  • 402
  • 512
2

If you're just developing or debugging and need a quick one-liner

throw 'Error message' unless thing == expected

Jason L.
  • 1,125
  • 11
  • 19