Sunday, March 27, 2011

Asserts in Rails from models or controllers?

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.

From stackoverflow
  • Beyond these, you mean?

    Gordon Wilson : I believe the OP is talking about asserts in the main code, as opposed to test assertions.
    Craig Stuntz : Hard to tell, isn't it? :)
    Gordon Wilson : a little, yeah ; )
    Readonly : Ah sorry about that. I've updated the question to be more clear.
  • 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.

  • Raise exceptions, and use rescue_from.

0 comments:

Post a Comment