1
0

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 1 year has passed since last update.

RSpec導入手順 コントローラテスト

Last updated at Posted at 2022-03-17

序文

RSpecを初めて使ってみましたので手順を残します。

コントローラを作りましょう

class Api::V1::TheDogController < ApplicationController

  def index
    render json: { breed: 'shepard'}
  end

end

route.rbのパスを通しましょう。

Gemfileにrspecを入れましょう

group :development do
   gem 'rspec-rails'
end

specファイルを作りましょう

rails g rspec:install 
rails g rspec:controller the_dog

require 'rails_helper'

RSpec.describe Api::V1::ThdDogController do
  render_views
  describe "GET /index" do
    it do
      request.env["HTTP_ACCEPT"] = 'application/json'
      get :index, format: :json, params: { call: "oh my dog"}
      json = JSON.parse(response.body)
      p json
      expect(json["breed"]).to eq "shepard"
    end
  end
end

テスト環境設定

テスト環境の設定ができているか見直しましょう.
環境依存ですが、筆者の場合は下記が必要でした

  • config/database.ymlにテスト用のDBを指定
  • credetialのtest.yml.encの設定
  • config/settings/test.yml
  • rails db:environment:set RAILS_ENV=test

テスト実行

bundle exec rspec
1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?