Hi I’m currently going through a tutorial on unit tests. I have two models: Song and Album.
class Song < ActiveRecord::Base
attr_accessible :title, :duration_in_seconds
belongs_to :album
end
class Album < ActiveRecord::Base
attr_accessible :artist, :title
has_many :songs
def duration
songs.sum(&:duration_in_seconds)
end
end
This is the test that’s supposed to pass:
require 'test_helper'
class AlbumTest < ActiveSupport::TestCase
test "should be able to report duration based on combined duration of its songs" do
album = Album.create
3.times do
album.songs.create(:duration_in_seconds => 5)
end
assert_equal 15, album.duration
end
end
As you see in the Album model, there is a method called duration. I have two questions about that.
- So we know that Song belongs to Album. If I do a method on an instance of Album, I can just access the songs of that instance in that method directly like that? The method definition looks weird… @album.duration would return @album.songs.sum(&:duration_in_seconds)? Lets say I had this method in my Album method:
def name_of_album
title
end
If I called @album.name_of_album would it be the same as @album.title?
- What’s with the
&in the duration method? Is it the same assongs.sum(:duration_in_seconds)?
The ampersand is part of Ruby and when it’s used in front of a symbol, it converts it to a
Proc.See http://railscasts.com/episodes/6-shortcut-blocks-with-symbol-to-proc?view=asciicast for more details.