Guest User

Untitled

a guest
Jan 19th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. # frozen_string_literal: true
  2.  
  3. require 'surrealist'
  4.  
  5. class DogeSerializer < Surrealist::Serializer
  6. json_schema do
  7. { name: String, name_length: Integer }
  8. end
  9.  
  10. def name_length
  11. name.length
  12. end
  13. end
  14.  
  15. class Doge
  16. include Surrealist
  17. attr_reader :name
  18.  
  19. surrealize_with DogeSerializer
  20.  
  21. def initialize(name)
  22. @name = name
  23. end
  24. end
  25.  
  26. RSpec.describe Surrealist::Serializer do
  27. describe 'Explicit surrealization through `Serializer.new`' do
  28. describe 'instance' do
  29. let(:instance) { Doge.new('John') }
  30. let(:expectation) { { name: 'John', name_length: 4 }.to_json }
  31. subject(:json) { DogeSerializer.new(instance).surrealize }
  32.  
  33. it { is_expected.to eq(expectation) }
  34. it_behaves_like 'error is raised for invalid params: instance'
  35. it_behaves_like 'error is not raised for valid params: instance'
  36. end
  37.  
  38. describe 'collection' do
  39. let(:collection) { [Doge.new('John'), Doge.new('Josh')] }
  40. let(:expectation) { [{ name: 'John', name_length: 4 }, { name: 'Josh', name_length: 4 }].to_json }
  41. subject(:json) { DogeSerializer.new(collection).surrealize }
  42.  
  43. it { is_expected.to eq(expectation) }
  44. it_behaves_like 'error is raised for invalid params: collection'
  45. it_behaves_like 'error is not raised for valid params: collection'
  46. end
  47. end
  48.  
  49. describe 'Implicit surrealization using .surrealize_with' do
  50. describe 'instance' do
  51. let(:instance) { Doge.new('George') }
  52. let(:expectation) { { name: 'George', name_length: 6 }.to_json }
  53. subject(:json) { instance.surrealize }
  54.  
  55. it { is_expected.to eq(expectation) }
  56. it_behaves_like 'error is raised for invalid params: instance'
  57. it_behaves_like 'error is not raised for valid params: instance'
  58. end
  59.  
  60. describe 'collection' do
  61. let(:collection) { [Doge.new('Wow'), Doge.new('Doge')] }
  62. let(:expectation) { [{ name: 'Wow', name_length: 3 }, { name: 'Doge', name_length: 4 }].to_json }
  63. subject(:json) { Surrealist.surrealize_collection(collection) }
  64.  
  65. it { is_expected.to eq(expectation) }
  66. end
  67. end
  68. end
Add Comment
Please, Sign In to add comment