【RSpec】リクエストスペック~APIのテスト~
リクエストのテスト
spec/requests配下にAPIのディレクトリをつくり、そこに各エンドポイントのファイルを作る。
# spec/requests/api/v1/articles_spec.rb RSpec.describe 'Api::V1::Articles', type: :request do describe 'GET /articles' do let(:article_num) { 10 } before do user = create(:user) create_list(:article, article_num, user: user) # 複数のファクトリを一気に作る end it 'returns fincle articles in json format' do get api_v1_articles_path, headers: { CONTENT_TYPE: 'application/json', ACCEPT: 'application/json', } expect(JSON.parse(body)['data'].count).to eq(article_num) # JSON.parse(body)でjsonをrubyに変換している expect(response).to be_successful expect(response).to have_http_status(:ok) end end end
リクエストヘッダーが必須。
bodyオブジェクトからレスポンスボディの内容を取得できる。
responseオブジェクトでHTTPステータスの検証をする。