How to write a custom test assertion in Ruby/Rails

| No Comments | No TrackBacks

At my job, we test a lot. Unit tests are code, and should be treated as well as the rest of your code. This often means writing custom assertions to keep repetition out of the individual test cases.

When I started writing custom assertions, I did them the easy way:

  def assert_includes(collection, item, message = nil)
    assert collection.include?(item), message || "#{collection.inspect} should include #{item.inspect}."
  end

Unfortunately, this looks and acts just slightly different from a normal assertion:

    1) Failure:
  [1, 2] should include 3.
  <false> is not true.

Lucky for us, Test::Unit is nice enough to provide the building block that it uses for all of its assertions. The snippet is a little longer, but more idiomatic:


  def assert_includes(collection, item, msg = nil)
    full_message = build_message(msg, "? should include ?.", collection, item)
    assert_block(full_message) do 
      collection.include?(item)
    end
  end

This looks much better:

    1) Failure:
  [1, 2] should include 3.

No TrackBacks

TrackBack URL: http://blog.uberweiss.net/admin/mt-tb.cgi/27

Leave a comment