LoginSignup
19
13

More than 5 years have passed since last update.

RSpec + Factory_botでテストする方法

Last updated at Posted at 2018-03-07

RSpecとFactory_botを使用したテスト方法。要点のみ。

当記事の動作環境
OS: macOS High Sierra 10.13.3

Ruby 2.4.2p198
Rails 5.1.5

rspec (3.7.0)
rspec-core (3.7.1)
rspec-expectations (3.7.0)
rspec-mocks (3.7.0)
rspec-rails (3.7.2)
rspec-support (3.7.1)

factory_bot (4.8.2)
factory_bot_rails (4.8.2)

RSpecとは

Ruby用のテスティングフレームワーク。
Ruby on railsには標準でminitestが搭載されているが、より多く使われているのはRSpec(主観)

Factory_botとは

テストデータ作成ツール。
もともとはFactory_girlという名称だったが変更になった。

事前準備

RSpecを使用してテストを行うため以下の設定が必要。
今回の記事では使用しないGemもあるが、今後のために先に入れておく。

Gemfile
group :development, :test do
  gem 'factory_bot_rails'
  gem "rspec-rails"
  gem "guard-rspec"
  gem "spring-commands-rspec"
end

group :test do
  gem "faker"
  gem "capybara"
  gem "database_cleaner"
  gem "launchy"
  gem "selenium-webdriver"
  gem "shoulda-matchers"
end

RSpecをインストール

$ bundle exec rails generate rspec:install

テスト方法

テストデータの準備

spec/factories.rb
FactoryBot.define do
  factory :staff do
    staff_last_name  "名字"
    staff_first_name "名前"
    staff_short_name "名字"
    position_div "2"
    create_id "TEST01"
    update_id "TEST01"
    lock_version "1"
  end
end
*_spec.rb
# テストコード内でのデータ生成方法

# DBへレコードを追加
FactoryBot.create :staff
# モデルのみの生成
FactoryBot.build :staff

# 生成したデータをコンソール出力する場合
@staff = create :staff
p @staff

テストコードの作成

spec/requests/staffs_controller_spec.rb
require "rails_helper"

describe StaffsController, :type => :request do

  describe "GET index" do
    before do
      FactoryBot.create :staff
    end

    it 'リクエストが成功すること' do
      get staffs_url
      expect(response.status).to eq 200
    end

    it '@staffが取得できていること' do
      get '/sales-system/staffs?position_div=2'
      expect(response.body).to include "レスポンスに含まれている名前"
    end

  end
end

テスト実行

# spec/*/*_spec.rbを全て実行
$ rails spec
/Users/kodai/.rbenv/versions/2.4.2/bin/ruby -I/Users/kodai/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/rspec-core-3.7.1/lib:/Users/kodai/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/rspec-support-3.7.1/lib /Users/kodai/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/rspec-core-3.7.1/exe/rspec --pattern spec/\*\*\{,/\*/\*\*\}/\*_spec.rb

StaffsController
  GET index
I, [2018-03-05T00:40:04.626323 #38686]  INFO -- : Started GET "/sales-system/staffs" for 127.0.0.1 at 2018-03-05 00:40:04 +0900
    リクエストが成功すること
I, [2018-03-05T00:40:04.774848 #38686]  INFO -- : Started GET "/sales-system/staffs?position_div=2" for 127.0.0.1 at 2018-03-05 00:40:04 +0900
    @staffが取得できていること

Finished in 0.73985 seconds (files took 8.59 seconds to load)
2 examples, 0 failures

方針

modelのvalidateや、controllerのlogicが正しいことより
常にリクエストのレスポンスが200であることの方が重要だと思うのでmodelやコントローラのテストは端折ってしまいます。

19
13
2

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
19
13