Skip to content

Instantly share code, notes, and snippets.

@coryodaniel
Last active February 8, 2016 23:23
Show Gist options
  • Select an option

  • Save coryodaniel/52fe5086ddcbedbbdcfa to your computer and use it in GitHub Desktop.

Select an option

Save coryodaniel/52fe5086ddcbedbbdcfa to your computer and use it in GitHub Desktop.
rails-api/active_model_serializers rspec matcher
# expect(json).to have_serialized(post).with(PostSerializer)
RSpec::Matchers.define :have_serialized do |unserialized|
# The serializer to use on the resource
chain :with do |serializer|
@serializer = serializer
end
# The serializer to use on the collection
chain :wrap do |collection_serializer|
@collection_serializer = collection_serializer
end
def serialize(object)
@collection_serializer ||= ActiveModel::Serializer::CollectionSerializer
if object.respond_to?(:map)
serializer = @collection_serializer.new(object, serializer: @serializer)
else
serializer = @serializer.new(object)
end
json = ActiveModel::Serializer::Adapter::JsonApi.new(serializer).to_json
JSON.parse(json)
end
match do |serialized|
serialized == serialize(unserialized)
end
failure_message do |serialized|
<<-FAIL.strip_heredoc
expected:
#{serialized}
to match:
#{serialize(unserialized)}
---
#{inspect}
FAIL
end
failure_message_when_negated do |serialized|
<<-FAIL.strip_heredoc
expected
#{serialized}
not to match:
#{serialize(unserialized)}
---
#{inspect}
FAIL
end
def inspect
<<-INSPECT.strip_heredoc
Using object serializer: #{@serializer}
Using collection serializer: #{@collection_serializer}
INSPECT
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment