2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ActiveModel::SerializerのRspec

Posted at

はじめに

SerializerのRSpecについて備忘録で残しておきます。

参考にしたのはこちらのドキュメント

ソースコード

Serializerを使って、idnameemailのみを返すjsonを実装しました。

user_serializer.rb
class UserSerializer < ActiveModel::Serializer
  attribute :id
  attribute :name
  attribute :email
end

そのテストコードがこちら

ポイントだと思うところはこちらの2つ

  1. Serializerのインスタンスを生成する必要がある
  2. .to_jsonメソッドのオプションを使用して、返ってくるデータのカラムを指定する必要がある

アソシエーションがある場合は、includeオプションを利用するとうまいこと書けると思います。

user_serializer_spec.rb
require 'rails_helper'

RSpec.describe "UserSerializer", type: :serializer do
  context "when create user" do
    let(:user) { create(:user) }
    it "matches to serialized JSON" do
      serializer = UserSerializer.new(user)
      expect(serializer.to_json).to eq(user.to_json(:only => [:id, :name, :email]))
    end
  end
end
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?