Skip to content

Commit

Permalink
Add specs for many_to_many associations
Browse files Browse the repository at this point in the history
  • Loading branch information
nesaulov committed Dec 4, 2017
1 parent 97a721e commit b5c1137
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
23 changes: 23 additions & 0 deletions spec/orms/sequel/models.rb
Expand Up @@ -22,10 +22,22 @@
String :label_name
end

DB.create_table :songs do
primary_key :id
String :length
String :title
end

DB.create_table :artists_songs do
foreign_key :artist_id, :artists, null: false
foreign_key :song_id, :songs, null: false
end

class Artist < Sequel::Model
include Surrealist

one_to_many :albums
many_to_many :songs

json_schema { { name: String } }
end
Expand All @@ -47,12 +59,23 @@ class Label < Sequel::Model
json_schema { { label_name: String } }
end

class Song < Sequel::Model
include Surrealist

many_to_many :artists

json_schema { { title: String } }
end

7.times { |i| Artist.insert(name: "Artist #{i}", age: (18 + i * 4)) }

Artist.each_with_index do |artist, i|
artist.add_album(title: "Album #{i}", year: (1950 + i * 5))
2.times { |t| artist.add_song(title: "Song #{i}#{t}", length: (120 + i * 5)) }
end

Album.each_with_index do |album, i|
Label.new(label_name: "Label #{i}", album_id: album.id).save
end

Song.each { |song| song.add_artist(Artist.last) }
36 changes: 36 additions & 0 deletions spec/orms/sequel/sequel_spec.rb
Expand Up @@ -256,5 +256,41 @@
end
end
end

describe 'many to many' do
let(:subject) { Surrealist.surrealize_collection(collection) }

context 'Artist -> Songs' do
let(:collection) { Artist.first.songs }
let(:result) { [{ title: 'Song 00' }, { title: 'Song 01' }].to_json }

it { is_expected.to eq(result) }
it_behaves_like 'error is not raised for valid params: collection'
it_behaves_like 'error is raised for invalid params: collection'

context '.where' do
let(:collection) { Artist.where(songs: Song.last(2)) }
let(:result) { [name: 'Artist 6'].to_json }

it { is_expected.to eq(result) }
end
end

context 'Song -> Artists' do
let(:collection) { Song.first.artists }
let(:result) { [{ name: 'Artist 0' }, { name: 'Artist 6' }].to_json }

it { is_expected.to eq(result) }
it_behaves_like 'error is not raised for valid params: collection'
it_behaves_like 'error is raised for invalid params: collection'

context '.where' do
let(:collection) { Song.where(artists: Artist.first(1)) }
let(:result) { [{ title: 'Song 00' }, { title: 'Song 01' }].to_json }

it { is_expected.to eq(result) }
end
end
end
end
end

0 comments on commit b5c1137

Please sign in to comment.