Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I write rails tests with the def or test keyword?

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.

like image 704
Anon Avatar asked Jul 31 '09 17:07

Anon


2 Answers

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.

like image 181
ryanb Avatar answered Nov 14 '22 23:11

ryanb


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!

like image 31
Yuval Karmi Avatar answered Nov 14 '22 22:11

Yuval Karmi