33
32

More than 5 years have passed since last update.

RailsでRSpecテストを実行するまで

Last updated at Posted at 2018-05-04

これまで全くテストを書かずにアプリ制作を進めてしまっていたので,勉強も兼ねてRSpecを導入してみました.
細かい設定はさておき,とりあえず1つテストを動かしてみることを目標にします.

環境

OS macOS 10.13.4
ruby 2.5.0
rails 5.1.5

railsアプリはすでに作成済みとします.

gemのインストール

Gemfile
group :development, :test do
  ~
  gem 'rspec-rails'
end
command
bundle install

RSpecのインストール

command
rails g rspec:install

specファイルの作成

今回はmodelのテストを書いてみます.

command
rails g rspec:model [model_name]

spec/models/[model_name]_spec.rbというファイルが作成されます.

テストの作成

とりあえずテストで期待する振る舞いだけ記述してみます.
describeブロックの中でitに続けて振る舞いを書きます.
(競馬のアプリを作ってるのでサンプルはそれに依ってます)

horse_spec.rb
require 'rails_helper'

RSpec.describe Horse, type: :model do
  it 'gets gate class depends on gate number'
end

試しにrspecを実行してみます.

command
bundle exec rspec

すると

Pending: (Failures listed here are expected and do not affect your suite's status)

  1) Horse gets gate class depends on gate number
     # Not yet implemented
     # ./spec/models/horse_spec.rb:4


Finished in 0.00956 seconds (files took 4.74 seconds to load)
1 example, 0 failures, 1 pending

テスト内容を記載していないのでpendingとして扱われます.
ともかく,最初のテストを作成することが出来ました.

テストの実装

ではテストを実装していきます.
modelのインスタンスを生成して,メソッドの戻り値を検証するテストです.

horse_spec.rb
require 'rails_helper'

RSpec.describe Horse, type: :model do
  it 'gets gate class depends on gate number' do
    horse = Horse.new(1, 2, 'キタサンブラック', '牡5 57 武豊', '1.9(1人気)')
    expect(horse.get_gate_class).to eq 'horse-table gate-number'
  end
end

再度テストを実行すると

Finished in 0.00344 seconds (files took 0.6508 seconds to load)
1 example, 0 failures

無事テストを成功させることが出来ました.

最後に

今回はとりあえずテストを動かすことにピンを留めてやってみました.
ですので,RSpecの良さをほとんど活かせてないと思います.
いつかRSpecのメリットを伝えられる記事を書けるようになりたいなあ.おわり.

33
32
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
33
32