ActiveModel :: Serializer Rspec gave an example of how to write a test. However, I've stumbled upon writing a test for another Serializer, so I'll post it.
In this example, assume that Article and Category have a many-to-many relationship and have an intermediate model called ʻarticle_category.rb`.
article.rb
class Article < ApplicationRecord
has_many :article_categories
has_many :categories, through: :article_categories
end
article_serializer.rb
class ArticleSerializer < ActiveModel::Serializer
attributes :id, :title
has_many :categories
end
When I write the test of this Serializer, it looks like this
article_serializer_spec.rb
require 'rails_helper'
RSpec.describe ArticleSerializer, type: :serializer do
context "When a new article is created" do
let(:article) { create(:article) }
let(:category) { create(:category) }
let(:article_category) do
create(:article_category, category: category, article: article)
end
it "Serialized JSON is created" do
serializer = ArticleSerializer.new(article)
expect(serializer.to_json).to eq(article.to_json(:only => [:id, :title], :include => { :category })
end
end
end
When I tested it, the returned JSON didn't contain the has_many related category and was left empty. why,,,
It seems that the way this test was written was bad, so I wrote it like this and it passed.
article_serializer_spec.rb
require 'rails_helper'
RSpec.describe ArticleSerializer, type: :serializer do
context "When a new article is created" do
let!(:article) { create(:article) }
let!(:category) { create(:category) }
let!(:article_category) do
create(:article_category, category: category, article: article)
end
it "Serialized JSON is created" do
serializer = ArticleSerializer.new(article)
expect(serializer.to_json).to eq(article.to_json(:only => [:id, :title], :include => { :category })
end
end
end
The change is that let is changed tolet!.
If you leave let as it is, the only object created in the example is ʻarticle. The reason is that let` creates an object only when it appears in the example.
So it's a good idea to use let! In an example like this!
Recommended Posts