0
0

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.

RSpecで可変長引数のテストがしたいとき

Last updated at Posted at 2019-11-21

動作確認環境: Ruby: 2.6系, Rspec: 3.8系, OSは問わないはずw

こんなとき

たとえば、グループで必須チェック(グループ内のいずれにも値が設定されない場合にエラーとする)を行うメソッドを作ったとき


require 'active_support'
require 'active_support/core_ext'
 
 
class Validator
  def required_group(data, *columns)
    joined_columns = columns.join('と')
    flg_present = false
    columns.each do |column|
      flg_present |= data[column].present?
    end
    return "#{joined_columns}のうちいずれか1つは入力必須です" unless flg_present
  end
end

RSpecではこう書くとよろしい


describe Validator do
  let(:target) { described_class.new }
  describe '#required_group' do
    subject { target.required_group(data, *columns) } # *がミソ
    let(:columns) { ['aaa', 'bbb'] }
    describe 'dataに' do
      context 'columnsで指定された列が存在しない場合' do
        let(:data) { 'hoge' => 'fuga' }
        it 'エラー文字列を返す' do
          is_expected.to eq 'aaaとbbbのうちいずれか1つは入力必須です'
        end
      end
      context 'columnsで指定された列が存在する場合' do
        context '指定された列の値が空でない場合' do
          let(:data) { 'hoge' => 'fuga', 'bbb' => 'got it!' }
          it 'nilを返すこと' do
            is_expected.to be_nil
          end
        end
      end
    end
  end
end

*を忘れるとcolumnsに配列([['aaa', 'bbb']])が渡された扱いとなるので、想定外の動きをします。
合掌

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?