Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 640
readonly Avatar asked Jan 28 '09 21:01

readonly


People also ask

What is assert in Ruby?

Ruby allows us to do things that any other compiled languages don't allow us. The best thing that Ruby provides is assertions. Ruby provides an assert() method for testing modules and can generate results whether a module is passed. Testing is one of the main parts of software development.

What type of test is not typical in a Rails application?

Integration. Don't try to test all the combinations in integration tests. That's what unit tests are for. Just test happy-paths or most common cases.

What is Minitest in Ruby on Rails?

What is Minitest? Minitest is a testing tool for Ruby that provides a complete suite of testing facilities. It also supports behaviour-driven development, mocking and benchmarking. With the release of Ruby 1.9, it was added to Ruby's standard library, which increased its popularity.

How do you run a Minitest in rails?

To run a Minitest test, the only setup you really need is to require the autorun file at the beginning of a test file: require 'minitest/autorun' . This is good if you'd like to keep the code small. A better way to get started with Minitest is to have Bundler create a template project for you.


1 Answers

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.

like image 146
Gordon Wilson Avatar answered Oct 14 '22 00:10

Gordon Wilson