hqt
hqt

Reputation: 30284

Meaning of "test do" syntax

I'm sorry if my question is silly because I just want to ask what does below line meaning in Ruby. (I'm reading a book about Rails as fast as possible for my course, so I don't have a firm grasp on the Ruby language.)

Here is a piece of code for unit test purpose:

class ProductTest < ActiveSupport::TestCase
  test "product attributes must not be empty" do   // this line I don't know
    product = Product.new
    assert product.invalid?
    assert product.errors[:title].any?
    assert product.errors[:description].any?
    assert product.errors[:price].any?
    assert product.errors[:image_url].any?
  end

The thing I want to ask is: At the line I don't know, the syntax test "...." do, what does it mean? Is it a function, method, class, something else?

Upvotes: 0

Views: 135

Answers (2)

oem
oem

Reputation: 386

This stuff is called a class macro, fancy name for a simple mechanism:

It is a class method (def self.test), that way you can use it in you class definition directly for example.

The normal way to write test cases (in Test::Unit) would be more like this:

def test_something_interesting
  ...
end

However, ActiveSupport (part of Rails) provides you this syntactical sugar so that you can write it like this:

test "something interesting" do
  ...
end

This method will then define a method with the name test_something_interesting.

You can find the implementation in Rails:

activesupport/lib/active_support/testing/declarative.rb

Upvotes: 2

Oscar Del Ben
Oscar Del Ben

Reputation: 4515

It's a block. Somewhere in the testing framework this method is defined:

def test(description, &block)
  # do something with block
end

I highly recommend that you pick a good Ruby book and that you read it slowly.

Upvotes: 2

Related Questions