LoginSignup
3
2

More than 3 years have passed since last update.

【Ruby on Rails】初心者でもメソッドの単体テストがしたい!!

Last updated at Posted at 2019-06-12

前置き

  • リクエスト単位でのテストより、メソッドレベルでのテストがやりたい!

Railsで「モジュールのメソッドレベルのテストがやりたいな〜」と思いながら、今まで保留していました。
テストを書きながら実装していこうとしている、この機会に調べてまとめてみました。

任意のモジュールを作成

sample_mod.rb
module SampleMod
  def add(a, b)
    a + b
  end
end

/spec 配下にテストファイルを格納

sample_mod_spec.rb
require 'rails_helper'

describe SampleMod do
  let(:test_class) { Struct.new(:sample_mod) { include SampleMod } }
  let(:hoge) { test_class.new } # hoge.メソッド名 でモジュール内の各メソッドを呼び出せる

  it 'サンプルテスト' do
    expect(hoge.add(1, 2)).to eq 3
  end
end

テスト実行

特定のファイルのみ実行

bundle exec rspec spec/path/to/sample_mod_spec.rb

タグ付け

タグ付けして特定のテストのみを実行することも出来る

sample_mod_spec.rb
require 'rails_helper'

describe SampleMod do
  let(:test_class) { Struct.new(:sample_mod) { include SampleMod } }
  let(:hoge) { test_class.new } 

  it 'サンプルテスト' do
   expect(hoge.add(1, 2)).to eq 3
  end

  it 'タグ1', fruits: :apple do
    expect('a').to eq 'a'
  end

  it 'タグ2', fruits: :orange do
    expect('a').to eq 'a'
  end
end

タグ1のみ実行

 bundle exec rspec --tag fruits:'apple' spec/path/to/sample_mod_spec.rb

タグ1、タグ2を実行

 bundle exec rspec --tag fruits spec/path/to/sample_mod_spec.rb

describeの部分にタグ付けしてグループ化することもできる

sample_mod_spec.rb
describe SampleMod do
  let(:test_class) { Struct.new(:sample_mod) { include SampleMod } }
  let(:hoge) { test_class.new } 

  describe 'テストだよ' fruits: 'apple' do
    it 'テスト1' do
      expect(hoge.add(1, 2)).to eq 3
    end

    it 'テスト2'
      expect('a').to eq 'a'
    end

    it 'テスト3'
      expect('a').to eq 'a'
    end
  end
end

テスト1〜3を全て実行

bundle exec rspec --tag fruits spec/path/to/sample_mod_spec.rb

タグの複数指定

--tag を指定する分だけ繰り返す。いずれかに合致するものがテストされる

bundle exec rspec --tag fruits --tag bird:crow spec/path/to/sample_mod_spec.rb

参考文献

3
2
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
3
2