How to use Gem included when developing Rails API server (rack-cors, rspec-rails, factory_bot_rails, rubocop)

Premise

Building Rails API server environment using docker-compose I didn't mention Gem much in this article, so continue

Editing Gemfile

Install the following 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 Required when using postman. If you don't do it, a CORS problem will occur and an error will occur.

config > initializers > cors.rb If you write as follows, you can hit the API from anywhere.

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 Since there is a file that is automatically generated when generating a model or controller, it is better to put it in advance.

rspec-rails GitHub Rails 5 uses 3 series of rspec-rails. (4 ~ in Rails 6)

After bundler install, the initial file below? Installation

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

Also added the following to .rspec and application.rb

See Procedure for installing Rspec and Factory_bot in Rails app

.rspec:.rspec


--color
--require rails_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

The model test was automatically generated, The integration test was manually created for writing in Request spec.

spec > requests > hoge_api_spec.rb I named it like this.

The request spec was written with the following configuration

hoge_spec.rb


RSpec.describe 'HogeAPI' do
  describe 'POST #create' do #Show action name
    context 'If xxx' do #conditions
      before do
        #Prepare dummy data
        FactoryBot.create(:hoge)
        ...
      end

      it 'yy' do
        expect do #When detecting a change in 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) #Check the status code
      end
    end

reference

[Rspec] Rails model test basics [Rails] How to write API test Test API using RSpec How to create test data using FactoryBot in Rails project

How to write application.rb that was useless

Since the generators in application.rb just don't want to generate the controller test file to generate the controller, Refer to Everyday Rails-Introduction to Rails Testing with RSpec

application.rb


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

At first I wrote, but the controller generation was as expected, but for some reason the model test file could not be generated due to an error.

rubocop Since rubocop is also used when formatting with VS Code, I installed it locally.

It will check if the file is written correctly.

//When you want to check
rubocop

//When you can check and fix it automatically
rubocop -a

It's a very warning, so check the content of the warning and set it to skip if it is unnecessary.

Example

.yml:.rubocop.yml


AllCops:
    Exclude: #Specify the files you want to exclude in 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 is a setting common to all warnings

reference

Set CORS for API in Rails Let's use RuboCop with Rails option and Lint option

Recommended Posts

How to use Gem included when developing Rails API server (rack-cors, rspec-rails, factory_bot_rails, rubocop)
[Rails] How to use gem "devise"
[Rails] How to avoid "Use hash rockets syntax" when executing Rubocop
How to use Chain API
[Rails] How to use enum
[Rails] How to use enum
How to use rails join
How to terminate rails server
[Rails] How to use validation
[Rails] How to use authenticate_user!
[Rails] How to use "kaminari"
[Rails] How to use Scope
[Rails 5] How to use gem gon ~ How to pass variables from Rails to JS ~
[Rails] How to use devise (Note)
[Rails] How to use flash messages
How to use Ruby on Rails
[Rails] How to use Active Storage
How to return Rails API mode to Rails
[Introduction to Rails] How to use render
How to use custom helpers in rails
[Ruby on Rails] How to use CarrierWave
[Rails] How to use rails console with docker
[Rails] How to use ActiveRecord :: Bitemporal (BiTemporalDataModel)
[Rails] How to use the map method
How to use MySQL in Rails tutorial
How to resolve errors when installing Rails 5.1.3
[Ruby on Rails] How to use redirect_to
[Note] How to use Rails 6 Devise + cancancan
[Ruby on Rails] How to use kaminari
[Rails] How to use video_tag to display videos
[Rails] How to use helper method, confimartion
How to use credentials.yml.enc introduced in Rails 5.2
[Rails] How to avoid "Use hash rockets syntax" when executing Rubocop
[Rails] How to write when making a subquery
[Rails] How to use select boxes in Ransack
How to use rails g scaffold, functions, precautions
How to use Java API with lambda expression
How to use JQuery in js.erb of Rails6
How to build API with GraphQL and Rails
[Rails] How to use Gem'rails-i18n' for Japanese support
[Ruby on Rails] How to use session method
[Rails] How to use PostgreSQL in Vagrant environment
[Ruby on Rails] How to stop when Rails server cannot be stopped by Ctrl + C
[rails] How to use devise helper method before_action: authenticate_user!
[Rails] I don't know how to use the model ...
Summary of Java communication API (1) How to use Socket
Summary of Java communication API (3) How to use SocketChannel
Summary of Java communication API (2) How to use HttpUrlConnection
[Docker + Rails] How to deal with Rails server startup failure
[Rails] How to install a decorator using gem draper