Ruby Language
순수 RSpec JSON API 테스트
수색…
Serializer 객체를 테스트하여 컨트롤러에 소개
jsonapi.org 스펙 을 따르기 위해 API를 빌드하고 결과가 다음과 같아야한다고 가정 해 보겠습니다.
{
"article": {
"id": "305",
"type": "articles",
"attributes": {
"title": "Asking Alexandria"
}
}
}
Serializer 객체에 대한 테스트는 다음과 같습니다.
# spec/serializers/article_serializer_spec.rb
require 'rails_helper'
RSpec.describe ArticleSerializer do
subject { described_class.new(article) }
let(:article) { instance_double(Article, id: 678, title: "Bring Me The Horizon") }
describe "#as_json" do
let(:result) { subject.as_json }
it 'root should be article Hash' do
expect(result).to match({
article: be_kind_of(Hash)
})
end
context 'article hash' do
let(:article_hash) { result.fetch(:article) }
it 'should contain type and id' do
expect(article_hash).to match({
id: article.id.to_s,
type: 'articles',
attributes: be_kind_of(Hash)
})
end
context 'attributes' do
let(:article_hash_attributes) { article_hash.fetch(:attributes) }
it do
expect(article_hash_attributes).to match({
title: /[Hh]orizon/,
})
end
end
end
end
end
Serializer 객체는 다음과 같이 보일 것입니다 :
# app/serializers/article_serializer.rb
class ArticleSerializer
attr_reader :article
def initialize(article)
@article = article
end
def as_json
{
article: {
id: article.id.to_s,
type: 'articles',
attributes: {
title: article.title
}
}
}
end
end
우리가 "serializer"사양을 실행할 때 모든 것이 통과됩니다.
그것은 꽤 지루합니다. 기사 Serializer에 오타를 소개합시다 type: "articles" 대신에 type: "events" 반환하고 테스트를 다시 시작하십시오.
rspec spec/serializers/article_serializer_spec.rb
.F.
Failures:
1) ArticleSerializer#as_json article hash should contain type and id
Failure/Error:
expect(article_hash).to match({
id: article.id.to_s,
type: 'articles',
attributes: be_kind_of(Hash)
})
expected {:id=>"678", :type=>"event",
:attributes=>{:title=>"Bring Me The Horizon"}} to match {:id=>"678",
:type=>"articles", :attributes=>(be a kind of Hash)}
Diff:
@@ -1,4 +1,4 @@
-:attributes => (be a kind of Hash),
+:attributes => {:title=>"Bring Me The Horizon"},
:id => "678",
-:type => "articles",
+:type => "events",
# ./spec/serializers/article_serializer_spec.rb:20:in `block (4
levels) in <top (required)>'
테스트를 실행하면 오류를 쉽게 발견 할 수 있습니다.
일단 오류를 수정하면 (예 : 유형을 article 정정 article ) 컨트롤러에 다음과 같이 소개 할 수 있습니다.
# app/controllers/v2/articles_controller.rb
module V2
class ArticlesController < ApplicationController
def show
render json: serializer.as_json
end
private
def article
@article ||= Article.find(params[:id])
end
def serializer
@serializer ||= ArticleSerializer.new(article)
end
end
end
이 예제는 다음 기사를 기반으로합니다 : http://www.eq8.eu/blogs/30-pure-rspec-json-api-testing
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow