attilagyorffy.com

Testing ActiveModel::Serializer classes with RSpec

Introduction

Attila Györffy

Attila Györffy

I'm a Ruby/JS dev/trainer with a focus on quality. An ex-Londoner, @terracycle, @ubxd, @lastfm. Follow me at http://twitter.com/attilagyorffy


Testing ActiveModel::Serializer classes with RSpec

Posted by Attila Györffy on .
Featured

Testing ActiveModel::Serializer classes with RSpec

Posted by Attila Györffy on .

ActiveModel::Serializer has been rewritten to support more complex serialisations, including the nice and shiny JSONAPI standard.

The upcoming version includes a new kind of abstraction, an Adapter. Basically, a serialiser is a class that defines what needs to be serialised (the attributes on the model) and the adapter controls how that model is serialised. Imagine you’d want to have a simple JSON serialized version as well as a JSONAPI or HAL+JSON version of a resource. This allows us to keep a separation of concerns.

Effectively, this also means that the work that happens in ActionController::Serialization has had to change. ActiveModel::Serialiser objects don’t receive to_json anymore, instead they are wrapped in an adapter class:

ActiveModel::Serializer::Adapter.create receives a serializer instance (that wraps our resource) and returns an instance of the right adapter, based on what adapter our application is using: ActiveModel::Serializer.config.adapter (in my case it’s :json_api)

This means to test your entire serialisation I suspect you’d need to change the way you write specs.

Given the following serializer:

We could test the full serialisation by wrapping our serializers with the necessary adapters in RSpecs tests.

To find out more about the upcoming version of ActiveModel::Serializers, subscribe to the rails-api mailing list and have a look at the project on GitHub.

Attila Györffy

Attila Györffy

https://attilagyorffy.com

I'm a Ruby/JS dev/trainer with a focus on quality. An ex-Londoner, @terracycle, @ubxd, @lastfm. Follow me at http://twitter.com/attilagyorffy

View Comments...