我是一名新手并且正在努力进行测试。我有3个班级,艺术家,歌曲和流派。我试图通过的测试如下:
test 'A genre has many artists' do
genre = Genre.new.tap{|g| g.name = 'rap'}
[1,2].each do
artist = Artist.new
song = Song.new
song.genre = genre
artist.add_song(song)
end
assert_equal genre.artists.count, 2
end
这是我的艺术家类,add_song方法是我需要调整的方法。当歌曲添加到艺术家时,我试图实例化一个新的类型对象,并将艺术家添加到该类型。目前不工作,当我调用genre.artists时,它返回一个空数组。 班级艺术家 attr_accessor:name,:songs,:genres,:genre,:artists @@ artists = []
def initialize(name = name, genre = genre)
@artists = []
@songs = []
@genre = genre
@genres = []
@name = name
@@artists << self
end
def self.all
@@artists
end
def self.reset_artists
@@artists = []
end
def self.count
self.all.size
end
def songs_count
self.songs.size
end
def count
self.size
end
def add_song(song)
@songs << song
@genres << song.genre
Genre.new(self)
end
end
class Genre
attr_accessor :name, :songs, :artists
@@genres = []
def initialize(artists = artists)
@songs = []
@artists = artists
@name = name
@@genres << self
end
def count
self.artists.count
end
def self.all
@@genres
end
def self.reset_genres
@@genre = []
end
end
class Song
attr_accessor :name, :genre, :artist
def initialize(name = name, artist = artist, genre = genre)
@name = name
@artist = artist
@genre = genre
end
end
答案 0 :(得分:0)
创建新艺术家时,将其添加到Artist::artists
- Artist
的类变量。您测试的数组是genre.artists
- 对象变量Genre
。这是与Artist::artists
不同的变量,我没有看到你在代码中的任何地方更新genre.artists
- 我很惊讶它甚至是一个数组,看到你没有将它初始化为数组。 ..
答案 1 :(得分:0)
您正在返回使用add_song
方法中的当前艺术家创建一个新的Genre实例。你可以通过几种方式让你的测试通过。
这会将艺术家添加到歌曲实例中引用的类型中。
def add_song(song)
@songs << song
@genres << song.genre
song.genre.artists << self
end
如果要从add_song方法返回新的Genre实例,第二个选项是修复测试。这很可能不是你想要的,但这会将艺术家设置为流派中的参考。
test 'A genre has many artists' do
genre = Genre.new.tap{|g| g.name = 'rap'}
[1,2].each do
art ist = Artist.new
song = Song.new
song.genre = genre
genre = artist.add_song(song)
end
assert_equal genre.artists.count, 2
end