6
4

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 3 years have passed since last update.

Ruby on Rails × DockerでRspecを導入

Last updated at Posted at 2020-09-10

目標

  • rails6 × docker 環境でrspecを導入したい

前提

  • Docker on mac
  • Ruby on Rails6

手順

1.Gemfileにgemを追加する

以下のgemを:develop, :testに追加する
gem "rspec-rails"
gem "factory_bot_rails"

/Gemfile

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # テストフレームワーク
  gem "rspec-rails"
  gem "factory_bot_rails"
end

2.サーバーを立ち上げているのとは別のターミナルからrspecをインストールする

MacBook-Air アプリ名 % docker-compose run web rails g rspec:install
Starting アプリ名_db_1 ... done
Running via Spring preloader in process 64
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb

これで設定ファイルがアプリのディレクトリに作られる

さっそくテストを作成してみる

modelのspecを書くため、ジェネレーターで生成してみる
まず以下のコマンドで関連ファイルが自動生成される。modelは自身のmodel.

MacBook-Air アプリ名 % docker-compose run web rails g rspec:model モデル名
Starting アプリ名_db_1 ... done
Running via Spring preloader in process 64
      create  spec/models/reception_spec.rb
      invoke  factory_bot
      create    spec/factories/receptions.rb

生成できたら今回はバリデーションに関するテストを書く

/spec/factories/reception.rb

FactoryBot.define do
  factory :reception do
    name {"サンプル訪問者1"}
    purpose {"面談"}
    organization {"サンプル株式会社"}
  end
end

/spec/models/reception_spec.rb

RSpec.describe Reception, type: :model do
  reception = FactoryBot.create(:reception)

  it 'receptionインスタンスが有効' do
    expect(reception).to be_valid
  end
end

specを追記したら、

MacBook-Air アプリ名 % docker-compose run web bundle exec rspec

で実行完了

MacBook-Air アプリ名 % docker-compose run web bundle exec rspec
Starting アプリ名_db_1 ... done
.

Finished in 0.22889 seconds (files took 6.32 seconds to load)
1 example, 0 failures

参考文献

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?