7
2

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 5 years have passed since last update.

Rubyでユニットテスト以外のところでassertを使いたい

Last updated at Posted at 2017-07-04

背景

ユニットテスト以外のところ、つまり通常のコード内で、条件が満たされなかったら例外を投げたい。
独自のassertメソッドを作ればできるけど、assert_equalassert_in_deltaなどたくさん作るのは面倒くさい。

minitestを使う方法

そこでminitestのassertをなんとか使えないかとやってみたのがこちら。

require "minitest"

# このモジュールの中に各種assertが定義されているのでinclude
include Minitest::Assertions

# それだけでうまくいくかと思いきや、self.assertionsが定義されていないとエラーになってしまった
class << self
  attr_accessor :assertions
end
self.assertions = 0


a = 1 + 2
assert_equal 3, a
# assert_in_delta Math::PI, (22.0 / 7.0), 0.00001, "これは失敗するはず"
# refute_empty [], "これも失敗するはず"```

確認したのは

  • Ruby 2.4.1
  • minitest 5.10.1

minitestの各種assertメソッドのリファレンス:http://www.rubydoc.info/gems/minitest/2.2.0/MiniTest/Assertions


RSpec Expectationsを使う方法

rspecはexpectationsの部分がライブラリとして切り出されていて、そちら単体でも使える。

gem install rspec
require "rspec/expectations"

include RSpec::Matchers

expect(1+2).to eq 3
expect(2+3).to eq 6
7
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
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?