jsonのキーをチェックするテストをrspecで書くときに、bodyがrenderされなくてはまった
テストが苦手な僕ですが、デグレが怖いので最低限戻り値程度のテストはしています。その時のお話。
環境
結論
- controllerのテスト時はviewをrenderせず
””
を返す - 上記の場合、
render_views
をdescribe/context直下に記入することで解決 - 但し、controllerから直接、
render json: @sth
としている場合は呼び出される
controllerの内容
module Api class AbcController < ApplicationController def index @abc = Abc.all() render json: @abc end end end
module Api class XyzController < ApplicationController def index @xyz = Xyz.all() render formats: :json, handlers: "jbuilder" end end end
jbuilderの内容は省略。ちゃんとあたいは帰っています。
specの内容
RSpec.describe Api::AbcController, type: :controller do context '/api/v1/abcs' do it 'returns json' do get :index # きちんとresponse.bodyが取れる expect(JSON.parse(response.body).keys).to include('id', 'name') end end end
RSpec.describe Api::XyzController, type: :controller do context '/api/v1/xyzs' do it 'returns json' do get :index # response.bodyが空 expect(JSON.parse(response.body).keys).to include('id', 'name') end end end
specは全く同じ。controllerの内容はrenderの部分が少し違う。これで下がエラー。結論は冒頭に
解決策
RSpec.describe Api::XyzController, type: :controller do context '/api/v1/xyzs' do + render_views it 'returns json' do get :index # response.bodyが空 expect(JSON.parse(response.body).keys).to include('id', 'name') end end end