views:

236

answers:

4

This seems like a simple question but I can't find the answer anywhere. I've noticed that in general, tests in a Ruby on Rails app can be written as:

  test "the truth" do
    assert true
  end

or

  def the_truth
    assert true
  end

It seems newer material writes tests the first way, but I can't seem to find a reason for this. Is one favored over the other? Is one more correct? Thanks.

+2  A: 

I believe the first method was implemented starting with Rails 2.2. As far as I am aware, it simply improves readability of your code (as def can be any function while test is used only in test cases). Good luck!

yuval
A: 

I would suggest doing your testing with either RSpec or Cucumber. I use both to test all my applications. RSpec is used to test the models and controllers, and Cucumber tests the Views (via the included Webrat functionality).

Mike Trpcic
A: 

As Mike Trpcic suggests you should check out RSpec and Cucumber. I'd like to add that you should also take a look at:

Shoulda is a macro framework for writing concise unit tests for your models/controllers, while the second is a replacement for fixtures.

jonnii
+7  A: 

There has been a shift in recent years from short, abbreviated test names to longer, sentence-like test names. This is partly due to the popularity of RSpec and the concept that tests are specs and should be descriptive.

If you prefer descriptive test names, I highly recommend going with the test method. I find it to be more readable.

test "should not be able to login with invalid password" do
  #...
end

def_should_not_be_able_to_login_with_invalid_password
  #...
end

Also, because the description is a string it can contain any characters. With def you are limited in which characters you can use.

ryanb