Testing the response for active_model_serializers
with version >= 0.10.0
I've done this simple helper for RSpec:
module AMSHelper
def ams_array_serializer(collection, options: {}, adapter: :json)
serializer = ActiveModel::Serializer::ArraySerializer.new(collection)
adapter_class = ActiveModel::Serializer::Adapter.adapter_class(adapter)
adapter_class.new(serializer, options)
end
def ams_serializer(object, options: {}, adapter: :json)
serializer = ActiveModel::Serializer.serializer_for(object).new(object)
adapter_class = ActiveModel::Serializer::Adapter.adapter_class(adapter)
adapter_class.new(serializer, options)
end
end
RSpec.configure do |config|
config.include AMSHelper, type: :request
end
So you can simply test with:
RSpec.describe "Posts", type: :request do
describe "GET /" do
it "returns http success" do
get posts_path
expect(response_body).to eq(ams_array_serializer(Post.all).to_json)
end
end
end
I hope this could be useful for someone.