Last active
April 26, 2019 16:55
-
-
Save roalcantara/6cd4f7d915102f3d50018606bb61d091 to your computer and use it in GitHub Desktop.
Rails5 > RSpec > ActiveModel::Serializers Raw
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# spec/support/active_model_serializers.rb | |
# inspired by: https://sonjapeterson.github.io/2016/03/19/testing-serializers.html | |
module SerializerSpecHelper | |
def serialize(obj, opts = {}) | |
serializer_class = opts.delete(:serializer_class) || "#{obj.class.name}Serializer".constantize | |
serializer = serializer_class.send(:new, obj) | |
serializer.serializable_hash.with_indifferent_access | |
end | |
end | |
RSpec.configure do |config| | |
# ActiveModel Serializer Helper | |
config.include SerializerSpecHelper, type: :serializer | |
# set `:type` for serializers directory | |
config.define_derived_metadata(file_path: Regexp.new("/spec/serializers")) do |metadata| | |
metadata[:type] = :serializer | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/serializers/user_serializer.rb | |
class UserSerializer < ActiveModel::Serializer | |
attributes :id, :name | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# spec/serializers/user_serializer_spec.rb | |
require "rails_helper" | |
RSpec.describe UserSerializer do | |
let(:user) { create :user } | |
subject { serialize(user) } | |
it { is_expected.to include(id: user.id, name: user.name) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you forgot to include
type: :serializer
in your spec