Zebra

One line tests without the smells.

The problem

context "A blog post" do
  setup do
    @author = create_person
    @post   = create_post :author => @author
  end

  should "be editable by its author" do
    assert @post.editable_by?(@author)
  end
end

Don’t see the problem?

Why bother writing self-documenting test code if you always have to explain it to the reader? Test names are essentially glorified comments and comments are frequently code smells. Furthermore, all the extra code required to create a test (should “” do … end) almost certainly discourages one assertion per test. If the assertion is one line and the code can explain itself, why bother with all the other crap?

The Solution

context "With a blog post" do
  setup do
    @author        = create_person
    @somebody_else = create_person
    @post          = create_post :author => @author
  end

  expect { @post.to be_editable_by(@author) }
  expect { @post.not_to be_editable_by(@somebody_else) }
end

But, what about the test name?

I’m glad you asked. This is where zebra gets really cool. The above test will create tests with the following names:

test: With a blog post expect @post.to(be_editable_by(@author))
test: With a blog post expect @post.not_to(be_editable_by(@author))

Now, that is self documenting code.

The right tool for the job

The cool thing about zebra is that it’s an extension to test/unit. If you have a test that belongs in a should block, with a big, old-fashioned test name, you can have it. Just use should or it. When you have a short, self-documenting test, use expect. Best of both worlds.

Dependencies

- jeremymcanally-context or shoulda
- parse_tree
- ruby2ruby

Inspiration

Jay Fields’ Expectations

Copyright © 2008 James Golick. See LICENSE for details.