LoginSignup
1
1

More than 5 years have passed since last update.

今更ながら,秘書BOTに単体テストを導入した

Last updated at Posted at 2018-08-23

背景

現在進行系で開発中の秘書BOT,今までテストクラスなるものを作ってませんでした
色んな理由で機能が肥大化してきたので,デグレしないことを視野に入れて,「せめて単体テストレベルだけでも・・・」と思い導入しました

導入したもの

Rubyにはデフォルトで単体テストができる機能がありますが,今回はそれを差し置いてRSpecを導入しました
その他,以下のgemを追加しました

  • RSpec(3.8.0)
  • rspec-parameterized(0.4.0)
  • simplecov(0.16.1)

RSpec

言わずと知れた(?)Rubyの単体テストができるテストツールです
具体的には,クラスやメソッド単位で実際に実行して検証することができます
今回はこれを使って,もくもくテストパターンを書いていきました

rspec-parameterized

RSpecにはパラメタライズドテストができないみたいなので,それをできるようにしてくれるgemです

simplecov

カバレッジを取ってくれます
どの行をテストしたかを見たいために導入してます

環境構築

gemのinstall

まずはGemfileに今回のgemを導入します

gem 'rspec'
gem 'rspec-parameterized'
gem 'simplecov'

そして,いつものようにbundleを実行します

$ bundle

これで単体テストができるようになる・・・様にはなっていません・・・
RSpecの初期化と他2gemの設定が要ります

RSpecの初期化

RSpecが使えるようにするには,初期化する必要があります
以下のコマンドを実行すると,初期化が行われます

$ rspec --init

実行すると,.rspecspec/spec_helper.rbというファイルが生成されます

.rspec
--require spec_helper
spec/spec_helper.rb
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
  # rspec-expectations config goes here. You can use an alternate
  # assertion/expectation library such as wrong or the stdlib/minitest
  # assertions if you prefer.
  config.expect_with :rspec do |expectations|
    # This option will default to `true` in RSpec 4. It makes the `description`
    # and `failure_message` of custom matchers include text for helper methods
    # defined using `chain`, e.g.:
    #     be_bigger_than(2).and_smaller_than(4).description
    #     # => "be bigger than 2 and smaller than 4"
    # ...rather than:
    #     # => "be bigger than 2"
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  # rspec-mocks config goes here. You can use an alternate test double
  # library (such as bogus or mocha) by changing the `mock_with` option here.
  config.mock_with :rspec do |mocks|
    # Prevents you from mocking or stubbing a method that does not exist on
    # a real object. This is generally recommended, and will default to
    # `true` in RSpec 4.
    mocks.verify_partial_doubles = true
  end

  # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
  # have no way to turn it off -- the option exists only for backwards
  # compatibility in RSpec 3). It causes shared context metadata to be
  # inherited by the metadata hash of host groups and examples, rather than
  # triggering implicit auto-inclusion in groups with matching metadata.
  config.shared_context_metadata_behavior = :apply_to_host_groups

# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
  # This allows you to limit a spec run to individual examples or groups
  # you care about by tagging them with `:focus` metadata. When nothing
  # is tagged with `:focus`, all examples get run. RSpec also provides
  # aliases for `it`, `describe`, and `context` that include `:focus`
  # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
  config.filter_run_when_matching :focus

  # Allows RSpec to persist some state between runs in order to support
  # the `--only-failures` and `--next-failure` CLI options. We recommend
  # you configure your source control system to ignore this file.
  config.example_status_persistence_file_path = "spec/examples.txt"

  # Limits the available syntax to the non-monkey patched syntax that is
  # recommended. For more details, see:
  #   - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
  #   - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
  #   - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
  config.disable_monkey_patching!

  # This setting enables warnings. It's recommended, but in some cases may
  # be too noisy due to issues in dependencies.
  config.warnings = true

  # Many RSpec users commonly either run the entire suite or an individual
  # file, and it's useful to allow more verbose output when running an
  # individual spec file.
  if config.files_to_run.one?
    # Use the documentation formatter for detailed output,
    # unless a formatter has already been configured
    # (e.g. via a command-line flag).
    config.default_formatter = "doc"
  end

  # Print the 10 slowest examples and example groups at the
  # end of the spec run, to help surface which specs are running
  # particularly slow.
  config.profile_examples = 10

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = :random

  # Seed global randomization in this process using the `--seed` CLI option.
  # Setting this allows you to use `--seed` to deterministically reproduce
  # test failures related to randomization by passing the same `--seed` value
  # as the one that triggered the failure.
  Kernel.srand config.seed
=end
end

.rspecにテストで使う設定ファイルの読み込みを行い,spec/spec_helper.rbで具体的なテストの設定を書くような感じです(多分)
テストを実行したときにカバレッジを取って欲しいので,spec/spec_helper.rbにカバレッジの設定を書き込みます

simplecovの設定

最終的にはこんな感じになりました

spec/spec_helper.rb
require 'simplecov'

SimpleCov.start

RSpec.configure do |config|
end

実際はRSpec.configureのブロックに色々書くのでしょうが,今回は不要でも動作するのですべて削除しました
個人的はSimpleCov.startがあるならSimpleCov.endもあってもいいじゃないか!思ってます(書いたら落ちます)

テストクラス作成

ここまで来たら,RSpecを使ってのテストが可能になります

完成形

いきなりですが,先に完成形から・・・
ファイル構成は以下です

│  .rspec
│  
├─lib
│      hello.rb
│      sample_test.rb
│      
└─spec
    │  spec_helper.rb
    │  
    └─lib
            hello_spec.rb(hello.rbをテストするクラス)
            sample_test_spec.rb(sample_test.rbをテストするクラス)

libにある各ソースの内容が以下です

sample_test.rb
require 'hello'

class SampleTest
  def get_text
    "sampleSample"
  end

  def calcate(mode, num1, num2)
    if mode.eql?("plus")
      num1 + num2
    elsif mode.eql?("minus")
      num1 - num2
    else
      'not mode'
    end
  end

  def get_hello
    hello = Hello.new
    hello.get_text
  end
end
hello.rb
class Hello
  def get_text
    'Hello!'
  end
end

これらに対してのテストクラスは以下です

sample_test_spec.rb
require 'rspec-parameterized'
require './spec/spec_helper'
require './lib/sample_test'

describe 'sample_test' do
  subject{SampleTest.new}

  # テストの基本形
  it 'get_text' do
    expect(subject.get_text).to eq 'sampleSample'
  end

  # パラメタライズドテスト
  using RSpec::Parameterized::TableSyntax
  where(:mode, :num1, :num2, :result_calculate) do
    'plus'  | 1  | 2 | 3
    'minus' | 3  | 1 | 2
    'plus'  | 10 | 1 | 11
    'mode'  | 5  | 7 | 'not mode'
  end

  with_them do
    it 'calcate' do
      expect(subject.calcate(mode, num1, num2)).to eq result_calculate
    end
  end

  # モックを利用したテスト
  it 'get_hello' do
    # Helloクラスのモックを用意
    hello_mock = instance_double(Hello)
    # Helloクラスのインスタンスが生成される時,モックを返す様にする
    allow(Hello).to receive(:new).and_return(hello_mock)
    # Helloクラスのget_textが呼び出された時,mocking_helloを返すようにする
    allow(hello_mock).to receive(:get_text).and_return('mocking_hello')
    expect(subject.get_hello).to eq 'mocking_hello'
  end
end
hello_spec.rb
require 'rspec-parameterized'
require './spec/spec_helper'
require './lib/hello'

describe 'hello' do
  subject{Hello.new}
  it 'get_text' do
    expect(subject.get_text).to eq 'Hello!'
  end
end

自分の理解も込めて普通のRubyでは見かけない,RSpec特有の記法を中心に説明してみます
ちなみに,テストが動くことを中心にしたいので,細かい動作とかは割愛です

describe/it

コメントに近いが,テストに失敗すると画面上にここに書かれた内容が表示されます
なので,どのクラスでどのメソッドのテストをするのかを記載して,テストに失敗したときの目印にできます
他にも似たようなもの(?)にcontextexampleとかありますが,今回は使えればいいのでこれら4つをどう使えばいいのかは割愛します
参考にしたのは

など,ぐぐったらたくさん出てきました

subject

テスト対象のオブジェクトやメソッドを設定できます
今回はオブジェクトにしました
これを使うと,何度もオブジェクトを生成したりする必要がなくなりDRYなテストコードでいい感じに書けました
さっき挙げたcontextexampleとかを駆使したらもっといい感じに書けるかもですが,今回は割愛

expect

RSpecで一番大事なところ
ここで実際にテストが実行されます
基本的な構文はexpect(テスト対象のメソッド).A B 期待値です
調べた中で,よく使いそうなAに入るのは以下です

構文 意味
to 期待値がBであること
not_to 期待値がBでないこと
to_not 期待値がBでないこと(not_toと同じ)

調べた中で,よく使いそうなBに入るのは以下です

構文 意味
eq 等しい
be >= 以上
be < 未満
be_truthy テスト対象がtrue(期待値不要)
be_falsey テスト対象がfalse(期待値不要)
raise_error 期待値の例外が発生

be 不等号を使っているのは以上と未満しか紹介していませんが,もちろん以下やより大きいも可能です
2つの表を参考にすると,テストクラスにあるexpect(subject.get_text).to eq 'sampleSample'は,
subject.get_textsampleSampleと等しい(である)こと」をテストしています

mock(モック)

RSpecで大事というよりも,単体テストというくくりで大事なところ
モックは特定のインスタンス生成やメソッドを呼び出した時,実際のソースの動作を行って値を返さずに実際のソースの動作を行わずにテストクラスで設定した値を返す機能のことです
ソースではsample_test#get_helloのテスト時にモックを利用しています

パラメタライズドテスト

RSpecというよりも,rspec-parameterizedの説明です
calcateメソッドのテストをするときに使用してます
テストデータが違うだけの時,非常に重宝します
今回は表のように使っているので,使う前にusing RSpec::Parameterized::TableSyntaxで使う宣言してから表を使わないと怒られます・・・
ちなみにテストの件数は行数と同じになるので,ここでは4件になります
テストが終わった後にまた別のテーブルを用意すると,前のテーブルは破棄されるようです
2回目以降はusing RSpec::Parameterized::TableSyntaxが不要です

simplecov

最後にカバレッジを取ってくれるsimplecovです
'spec'があるディレクトリで$ rspecと叩いて実行すると,同階層にcoverageが出来上がり,そこでカバレッジを確認することができます
HTMLが生成されるのですが,思いの外,速攻で出力されます
見た目は↓の画像になります

image.png
image.png

ソースの右側にはテストで通過した回数が載ってたりします

これからやりたいこと

単体テストができるようになったので,JenkinsのようなCIツールを使って自動でテストが実行されてデグレードを回避できる環境を作りたい・・・

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