Next add test for Helper.songs_as_json #105

Merged
merged 2 commits into from Mar 11, 2012
Jump to file or symbol
Failed to load files and symbols.
+69 −5
Diff settings

Always

Just for now

View
@@ -12,17 +12,24 @@ module Helpers
# songs - An Array of Songs.
# user - The User object of the currently logged-in user.
#
+ # songs and user are both required. If they are not the return JSON
+ # string will contain the "songs" key with an empty array.
+ #
# Returns a JSONified String.
def songs_as_json(songs,user)
- songs.map! do |song|
- song.starred = user.starred?(song)
- song.to_hash
+ if songs && user
+ songs.map! do |song|
+ song.starred = user.starred?(song)
+ song.to_hash
+ end
+ else
+ songs = nil
end
hash = {
- :songs => songs
+ :songs => songs || []
}
-
+
Yajl.dump hash
end
View
@@ -0,0 +1,57 @@
+require File.expand_path("../../helper", __FILE__)
+
+context "api/helpers" do
+ include Helpers
+
+ setup do
+ @songs = [
+ Song.new(:artist => 'Justice',
+ :name => 'Stress',
+ :album => 'Cross',
+ :id => 'xyz'),
+ Song.new(:artist => 'Deadmau5',
+ :name => 'Strobe',
+ :album => 'Skrillex covers',
+ :id => 'xyza')
+ ]
+ @user = User.create 'holman', 'zach@example.com'
+ end
+
+ test "valid songs_as_json with valid parameters" do
+ json = JSON.parse(songs_as_json @songs, @user)
+ songs = json["songs"]
+
+ assert_equal ["songs"], json.keys
+ assert_equal ["id", "name", "artist", "album", "starred", "queued"], songs[0].keys
+ assert_equal ["id", "name", "artist", "album", "starred", "queued"], songs[1].keys
+ assert_equal 2, songs.length
+
+ @songs.each_with_index do |song, index|
+ assert_equal song[:id], songs[index]["id"]
+ assert_equal song[:name], songs[index]["name"]
+ assert_equal song[:artist], songs[index]["artist"]
+ assert_equal song[:album], songs[index]["album"]
+ assert_equal false, songs[index]["starred"]
+ assert_equal false, songs[index]["queued"]
+ end
+ end
+
+ test "songs_as_json with empty parameters" do
+ json = JSON.parse(songs_as_json nil, nil)
+ assert_equal ["songs"], json.keys
+ assert_equal 0, json["songs"].length
+ end
+
+ test "songs_as_json with songs parameter only" do
+ json = JSON.parse(songs_as_json @songs, nil)
+ assert_equal ["songs"], json.keys
+ assert_equal 0, json["songs"].length
+ end
+
+ test "songs_as_json with user parameter only" do
+ json = JSON.parse(songs_as_json nil, @user)
+ assert_equal ["songs"], json.keys
+ assert_equal 0, json["songs"].length
+ end
+
+end