6

Is there a built-in way of specifying asserts in Rails that will throw an exception if an invariant is broken during development and testing?

Edit: Just to be clear, I'm looking for asserts that can be placed in models or controllers as opposed to asserts that you would use for unit tests.

readonly
  • 343,444
  • 107
  • 203
  • 205

4 Answers4

10

There are many assert functions if you are writing tests. But for assertiona in the main code, there aren't any and you can roll your own easily.

Add something like this to environment.rb:

class AssertFailure < Exception
end

def assert(message = 'assertion failed')
  unless block_given? and yield
    raise message
  end
end

and make it a no-op in your environments/production.rb so there is minimal overhead

def assert(message = 'assertion failed')
end

Then, in your code, you can assert to your heart's content:

assert { value == expected_value }
assert('value was not what was expected') { value == expected_value }

If value does not equal expected_value and you aren't running in production, an exception will be raised.

Shyam Habarakada
  • 15,367
  • 3
  • 36
  • 47
Gordon Wilson
  • 26,244
  • 11
  • 57
  • 60
  • I'm unsure if the assert method is intended to be a method of the AssertFailure class above or not. It doesn't look like it should, but if I use that code I get an "unexpected $end, expecting keyword_end" error. Can you please elaborate and indicate if require/include is needed for usage please? (also - it seems like a part of the application implementation - so is the config directory an appropriate place for such code?) – DavidJ Oct 03 '12 at 13:28
  • I think there should be an `end` line immediately after the `class` line. – dubek Oct 07 '12 at 06:56
  • Can you explain what the class declaration is doing there? how does it come into play? – Ben Wheeler Sep 23 '15 at 12:17
0

As @Gordon said, no there isn't. I ended up using the solid_assert gem by Jorge Manrubia, as mentioned in this question: Is it idiomatic Ruby to add an assert( ) method to Ruby's Kernel class?

Community
  • 1
  • 1
DavidJ
  • 4,369
  • 4
  • 26
  • 42
0

Beyond these, you mean?

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
0

Raise exceptions, and use rescue_from.

August Lilleaas
  • 54,010
  • 13
  • 102
  • 111