views:

222

answers:

3

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.

+1  A: 

Beyond these, you mean?

Craig Stuntz
I believe the OP is talking about asserts in the main code, as opposed to test assertions.
Gordon Wilson
Hard to tell, isn't it? :)
Craig Stuntz
a little, yeah ; )
Gordon Wilson
Ah sorry about that. I've updated the question to be more clear.
Readonly
+3  A: 

I don't believe there is. But, you can roll your own easily.

Add something like this to environment.rb:

class AssertFailure < Exception

def assert
  if RAILS_ENV != 'production' && !yield
    raise AssertFailure
  end
end

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

assert { value == expected_value }

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

Gordon Wilson
A: 

Raise exceptions, and use rescue_from.

August Lilleaas