Last active
October 22, 2020 07:42
-
-
Save brycesenz/9175431 to your computer and use it in GitHub Desktop.
Rspec tests & helpers for ActiveModel::Serializers
This file contains 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/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 |
This file contains 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/customer_serializer_spec.rb | |
require 'spec_helper' | |
describe CustomerSerializer do | |
let(:object) do | |
build_serializable( | |
:account_number => "ACT123", | |
:username => "newuser", | |
:email => "[email protected]", | |
) | |
end | |
subject { serialize(object) } | |
it { should include(:customer_number => "ACT123") } | |
it { should include(:username => "newuser") } | |
it { should include(:email => "[email protected]") } | |
end |
This file contains 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/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i get a NoMethod error for obj.stub on line 17 of serializer_example_group.rb