Skip to content

Commit f029cf7

Browse files
corinnekunzeshishirmk
authored andcommitted
Adding specs for #as_json method on ObjectSerializer and making sure non-included attributes are removed
1 parent 1e40b7d commit f029cf7

3 files changed

Lines changed: 40 additions & 2 deletions

File tree

.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,9 @@ doc
3333

3434
# For the gem
3535
test.db
36+
37+
# For those using rbenv
38+
.ruby-version
39+
40+
# For those who install gems locally to a vendor dir
41+
/vendor

spec/lib/object_serializer_spec.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,24 @@
8282
expect(serializable_hash['data']).to eq []
8383
end
8484

85+
describe '#as_json' do
86+
it 'returns a json hash' do
87+
json_hash = MovieSerializer.new(movie).as_json
88+
expect(json_hash['data']['id']).to eq movie.id.to_s
89+
end
90+
91+
it 'returns multiple records' do
92+
json_hash = MovieSerializer.new([movie, movie]).as_json
93+
expect(json_hash['data'].length).to eq 2
94+
end
95+
96+
it 'removes non-relevant attributes' do
97+
movie.director = 'steven spielberg'
98+
json_hash = MovieSerializer.new(movie).as_json
99+
expect(json_hash['data']['director']).to eq(nil)
100+
end
101+
end
102+
85103
it 'returns errors when serializing with non-existent includes key' do
86104
options = {}
87105
options[:meta] = { total: 2 }

spec/shared/contexts/movie_context.rb

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,13 @@
44
before(:context) do
55
# models
66
class Movie
7-
attr_accessor :id, :name, :release_year, :actor_ids, :owner_id, :movie_type_id
7+
attr_accessor :id,
8+
:name,
9+
:release_year,
10+
:director,
11+
:actor_ids,
12+
:owner_id,
13+
:movie_type_id
814

915
def actors
1016
actor_ids.map do |id|
@@ -56,6 +62,7 @@ class Account
5662
class MovieSerializer
5763
include FastJsonapi::ObjectSerializer
5864
set_type :movie
65+
# director attr is not mentioned intentionally
5966
attributes :name, :release_year
6067
has_many :actors
6168
belongs_to :owner, record_type: :user
@@ -135,7 +142,14 @@ class MovieSerializer
135142
# Movie and Actor struct
136143
before(:context) do
137144
MovieStruct = Struct.new(
138-
:id, :name, :release_year, :actor_ids, :actors, :owner_id, :owner, :movie_type_id
145+
:id,
146+
:name,
147+
:release_year,
148+
:actor_ids,
149+
:actors,
150+
:owner_id,
151+
:owner,
152+
:movie_type_id
139153
)
140154

141155
ActorStruct = Struct.new(:id, :name, :email)

0 commit comments

Comments
 (0)