Ruby’s standard testing suite, MiniTest, is in dire need of a quick-and-handy reference for its syntax. I’ve put one together comparing the unit
syntax (assert/refute) and the spec
syntax (must/wont). You can see it below or download the Google Spreadsheet I made and roll your own sheet (HTML, XLS)
Test syntax
Unit | Spec | Arguments | Examples |
---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Test Setup
Unit | Spec |
---|---|
setup() |
before(type = nil, &block) |
teardown() |
after(type = nil, &block) |
Mocks
via MiniTest::Mock
expect(name, retval, args=[])
– Expect that method name is called, optionally with args or a blk, and returns retval.Example:
@mock.expect(:meaning_of_life, 42) @mock.meaning_of_life # => 42 @mock.expect(:do_something_with, true, [some_obj, true]) @mock.do_something_with(some_obj, true) # => true @mock.expect(:do_something_else, true) do |a1, a2| a1 == "buggs" && a2 == :bunny end
verify
– Verify that all methods were called as expected. Raises MockExpectationError if the mock object was not called as expected.
Other syntax
def flunk(msg=nil)
def pass(msg=nil)
def skip(msg=nil, bt=caller)
def it (desc="anonymous", &block)
i_suck_and_my_tests_are_order_dependent!()
– Call this at the top of your tests when you absolutely positively need to have ordered tests. In doing so, you’re admitting that you suck and your tests are weak. (TestCase public class method)parallelize_me!()
– Call this at the top of your tests when you want to run your tests in parallel. In doing so, you’re admitting that you rule and your tests are awesome.make_my_diffs_pretty!()
– Make diffs for this TestCase use pretty_inspect so that diff in assert_equal can be more details. NOTE: this is much slower than the regular inspect but much more usable for complex objects.
Tutorials
- A MiniTest::Spec Tutorial: Elegant Spec-Style Testing, by Peter Cooper
- Minimalicious testing in Ruby 1.9 with MiniTest, by Arvid Anderson
- Minitest Quick Reference, by Matt Sears