Andrew
Andrew

Reputation: 38619

Ruby testing: block vs. method

As I've been writing test suites for a Rails app, I've noticed that there are two different ways to create tests, a test block and a regular method:

test "the truth" do
  assert true
end

vs.

def test_for_something_else
  assert true
end

Is there any difference between the two testing structures? When should I use one over the other?

Edit: On further inspection, tests written as methods are counted in rake:stats while those written with the test syntax are not. There's one difference…

Upvotes: 3

Views: 347

Answers (3)

Tim Fletcher
Tim Fletcher

Reputation: 7396

One difference/annoyance I have found is in Vim with Ctags and the TagList plugin. If your tests are not written as functions you can't quickly browse them using the :TlistToggle command. If you have a lot of tests in one file this can make quickly navigating them more difficult.

Upvotes: 0

John Topley
John Topley

Reputation: 115322

I think the block syntax was added due to the popularity of Behaviour-Driven-Development frameworks such as RSpec, with their more natural Should do X... syntax. In the end it's a matter of personal preference.

Upvotes: 4

liwp
liwp

Reputation: 6926

I would expect that technically there is no difference between the two. The former allows you to use a string to describe your test, whereas with the latter form you have to come up with a descriptive method name which are sometimes annoyingly long and hard to read [1]. Because of this difference I would personally prefer the former, but in the end it's down to personal / project preference.

[1] "add two interleaving timers that trigger in the opposite order" vs. test_addTwoInterleavingTimersThatTriggerInTheOppositeOrder(...)

Upvotes: 1

Related Questions