Skip to content

Instantly share code, notes, and snippets.

@leonelgalan
Last active October 14, 2016 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonelgalan/752f79a2e630b7281b7d1fe60e99dfe9 to your computer and use it in GitHub Desktop.
Save leonelgalan/752f79a2e630b7281b7d1fe60e99dfe9 to your computer and use it in GitHub Desktop.
require 'rails_helper'
ActiveModelSerializers.config.schema_path = 'spec/support/schemas'
module ActiveModelSerializers
module Test
module Schema
class AssertSchema
def controller_path
request.filtered_parameters.with_indifferent_access[:controller]
end
def action
request.filtered_parameters.with_indifferent_access[:action]
end
end
RSpec::Matchers.define :have_valid_schema do |schema_path|
match do
@matcher = AssertResponseSchema.new(schema_path || nil, request, response, nil)
@matcher.call
end
failure_message do
@matcher.message
end
end
end
end
end
module ActiveModelSerializers
module Test
module Serializer
extend ActiveSupport::Concern
def serializer_matches?(expectation)
@assert_serializer.expectation = expectation
@assert_serializer.message = message
@assert_serializer.response = response
@assert_serializer.matches?
end
def message
@assert_serializer.message
end
class AssertSerializer
def subscribe
@_subscribers << ActiveSupport::Notifications.subscribe(event_name) do |_name, _start, _finish, _id, payload|
serializer = payload[:serializer].name
serializers << serializer
return unless serializer == 'ActiveModel::Serializer::CollectionSerializer'
serializers << payload[:adapter].serializer.send(:options)[:serializer].name
end
end
end
RSpec::Matchers.define :use_serializer do |expected|
match do
serializer_matches?(expected)
end
failure_message do
message
end
end
end
end
end
describe V1::PostsController do
include ActiveModelSerializers::Test::Serializer
include ActiveModelSerializers::Test::Schema
describe '#index' do
before { get :index }
describe 'response' do
subject { response }
it { is_expected.to use_serializer V1::PostSerializer }
it { is_expected.to have_valid_schema }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment