Skip to content

Commit

Permalink
Adding specs for #as_json method on ObjectSerializer and making sure …
Browse files Browse the repository at this point in the history
…non-included attributes are removed
  • Loading branch information
corinnekunze authored and shishirmk committed Mar 13, 2018
1 parent 1e40b7d commit f029cf7
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,9 @@ doc

# For the gem
test.db

# For those using rbenv
.ruby-version

# For those who install gems locally to a vendor dir
/vendor
18 changes: 18 additions & 0 deletions spec/lib/object_serializer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,24 @@
expect(serializable_hash['data']).to eq []
end

describe '#as_json' do
it 'returns a json hash' do
json_hash = MovieSerializer.new(movie).as_json
expect(json_hash['data']['id']).to eq movie.id.to_s
end

it 'returns multiple records' do
json_hash = MovieSerializer.new([movie, movie]).as_json
expect(json_hash['data'].length).to eq 2
end

it 'removes non-relevant attributes' do
movie.director = 'steven spielberg'
json_hash = MovieSerializer.new(movie).as_json
expect(json_hash['data']['director']).to eq(nil)
end
end

it 'returns errors when serializing with non-existent includes key' do
options = {}
options[:meta] = { total: 2 }
Expand Down
18 changes: 16 additions & 2 deletions spec/shared/contexts/movie_context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@
before(:context) do
# models
class Movie
attr_accessor :id, :name, :release_year, :actor_ids, :owner_id, :movie_type_id
attr_accessor :id,
:name,
:release_year,
:director,
:actor_ids,
:owner_id,
:movie_type_id

def actors
actor_ids.map do |id|
Expand Down Expand Up @@ -56,6 +62,7 @@ class Account
class MovieSerializer
include FastJsonapi::ObjectSerializer
set_type :movie
# director attr is not mentioned intentionally
attributes :name, :release_year
has_many :actors
belongs_to :owner, record_type: :user
Expand Down Expand Up @@ -135,7 +142,14 @@ class MovieSerializer
# Movie and Actor struct
before(:context) do
MovieStruct = Struct.new(
:id, :name, :release_year, :actor_ids, :actors, :owner_id, :owner, :movie_type_id
:id,
:name,
:release_year,
:actor_ids,
:actors,
:owner_id,
:owner,
:movie_type_id
)

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

0 comments on commit f029cf7

Please sign in to comment.