Skip to content

Instantly share code, notes, and snippets.

@brycesenz
Last active October 22, 2020 07:42
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save brycesenz/9175431 to your computer and use it in GitHub Desktop.
Save brycesenz/9175431 to your computer and use it in GitHub Desktop.
Rspec tests & helpers for ActiveModel::Serializers
# app/serializers/customer_serializer_spec.rb
class CustomerSerializer < ActiveModel::Serializer
attributes :customer_number, :email, :username
def customer_number
object.account_number
end
def merchant_id
object.username.first(20)
end
end
# spec/serializers/customer_serializer_spec.rb
require 'spec_helper'
describe CustomerSerializer do
let(:object) do
build_serializable(
:account_number => "ACT123",
:username => "newuser",
:email => "email@service.com",
)
end
subject { serialize(object) }
it { should include(:customer_number => "ACT123") }
it { should include(:username => "newuser") }
it { should include(:email => "email@service.com") }
end
# spec/support/serializer_example_group.rb
module SerializerExampleGroup
extend ActiveSupport::Concern
included do
metadata[:type] = :serializer
let(:serializable_class) do
Class.new(OpenStruct) do
include ActiveModel::Serialization
end
end
def build_serializable(attributes={})
serializable_class.new(attributes).tap do |obj|
obj.stub(:read_attribute_for_serialization) { |name| attributes[name] }
end
end
def serialize(object)
described_class.new(object).serializable_hash.with_indifferent_access
end
end
RSpec.configure do |config|
config.include self,
:type => :serializer,
:example_group => { :file_path => %r(spec/serializers) }
end
end
@christophermlne
Copy link

i get a NoMethod error for obj.stub on line 17 of serializer_example_group.rb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment