LoginSignup
0
1

More than 1 year has passed since last update.

Rails APIサーバー開発時に入れたGemの使い方 (rack-cors, rspec-rails, factory_bot_rails, rubocop)

Last updated at Posted at 2020-09-26

前提

docker-composeを用いたRailsのAPIサーバー環境構築
この記事でGemについてはあまり触れなかったので続き

Gemfileの編集

下記のGemをインストールする。

...
gem 'rack-cors'

group :development, :test do
...
  gem 'rspec-rails', '~> 3.9'
  gem 'factory_bot_rails'
end

group :development do
...
  gem 'rubocop', require: false
end

rack-cors

postman使う時に必要。
やっておかないとCORS問題発生してエラー出る。

config > initializers > cors.rb
を以下のように書くと、どこからでもAPI叩けるようになる。

cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'

    resource '*',
             headers: :any,
             methods: %i[get post put patch delete options head]
  end
end

rspec-rails, factory_bot_rails

モデルやコントローラーをgenerateするときに自動生成するファイルがあるのであらかじめ入れておいた方が良い。

rspec-rails GitHub
Rails 5ではrspec-railsの3系を使用する。(Rails 6では4~)

bundler installしたら、以下で初期ファイル?インストール

rails generate rspec:install
…
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb

また以下を追加

参照 RailsアプリへのRspecとFactory_botの導入手順

rails_helper.rb
RSpec.configure do |config|
...
  config.include FactoryBot::Syntax::Methods
end
.rspec
--require spec_helper
--format documentation
application.rb
    config.generators do |g|
      g.test_framework :rspec,
                       view_specs: false,
                       helper_specs: false,
                       controller_specs: false,
                       routing_specs: false

モデルのテストは自動生成されたが、
結合テストはRequest specで書くために手動でファイルを作った。

spec > requests > hoge_api_spec.rb
のように名付けた。

リクエストスペックは以下のような構成で書いた

hoge_spec.rb
RSpec.describe 'HogeAPI' do
  describe 'POST #create' do # アクション名を示す
    context 'xxxな場合' do # 条件
      before do
        # ダミーのデータを用意
        FactoryBot.create(:hoge)
        ...
      end

      it 'yyする' do
        expect do # DBの変更を検知するときはくくる
          post '/hoge/create', params: { name: "Hoge" }
        end.to change(Hoge, :count).by(+1) and change(Table2, :count).by(0)
        expect(response.status).to eq(201) # ステータスコードの確認
      end
    end

参考

【rspec】Railsモデルテストの基本
【Rails】APIテストの書き方
RSpecを使ってAPIのテストを行う
Railsプロジェクトで、FactoryBotを用いたテストデータを作成する方法

ダメだったapplication.rbの書き方

application.rbのgeneratorsはcontrollerを生成するためにcontrollerのテストファイルを生成しないようにしたいだけなので、
Everyday Rails - RSpecによるRailsテスト入門を参考に

application.rb
# NG
    config.generators do |g|
      g.test_framework :rspec,
                       controller_specs: false

と最初は書いていたが、コントローラー生成は期待通りだったもののなぜかモデルのテストファイルがエラーで生成できなくなった。

rubocop

rubocopはVSCodeでFormatする時にも使うのでローカルにもインストールした。

ファイルの書き方が正しいかどうかを確認してくれる。

// 確認したい時
rubocop

// 確認して直せるところは自動でなおすとき
rubocop -a

めっちゃ警告でるので、警告の内容をみて不要であればスキップするように設定する。

.rubocop.yml
AllCops:
    Exclude: # 除外したいファイルは Exclude に指定する。
      - 'spec/*.rb'
      - 'db/schema.rb'
      - 'test/*'
      - 'config/**/*'
      - 'Gemfile'
      - 'bin/*'


Style/FrozenStringLiteralComment:
    Enabled: false

Style/Documentation:
    Enabled: false

Style/StringLiterals:
    Enabled: false

Metrics/BlockLength:
    Exclude:
        - 'spec/**/*'

Metrics/MethodLength:
    Max: 30

Metrics/AbcSize:
    Max: 30

Style/AsciiComments:
    Enabled: false

AllCopsは全ての警告に共通する設定

参考

RailsでAPIにCORSを設定する
RuboCopをRailsオプションやLintオプションで使ってみよう

0
1
0

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