Lou*_*hys 24 ruby string unit-testing ruby-on-rails
在Ruby单元测试中,如何断言字符串包含子字符串?就像是:
assert_contains string_to_test, substring_to_verify
Pat*_*ity 33
你可以去用assert_match pattern, string, [message]它,如果真string =~ pattern:
assert_match substring_to_verify, string_to_test
例如
assert_match /foo/, "foobar"
如果你经常使用它,为什么不写自己的断言?
require 'test/unit'
module Test::Unit::Assertions
  def assert_contains(expected_substring, string, *args)
    assert_match expected_substring, string, *args
  end
end
或者,使用@IvayloStrandjev描述的方法(更容易理解),您可以定义
require 'test/unit'
module Test::Unit::Assertions
  def assert_contains(expected_substring, string, *args)
    assert string.include?(expected_substring), *args
  end
end
用法完全按照您在问题中的要求使用,例如
class TestSimpleNumber < Test::Unit::TestCase
  def test_something
    assert_contains 'foo', 'foobar'
  end
  def test_something_fails
    assert_contains 'x', 'foobar', 'Does not contain x'
  end
end
哪个会产生
Run options:
# Running tests:
.F
Finished tests in 0.000815s, 2453.9877 tests/s, 2453.9877 assertions/s.
  1) Failure:
test_something_fails(TestSimpleNumber) [assertion.rb:15]:
Does not contain x
2 tests, 2 assertions, 1 failures, 0 errors, 0 skips
根据要求,使用自动消息:
module Test::Unit::Assertions
  def assert_contains(exp_substr, obj, msg=nil)
    msg = message(msg) { "Expected #{mu_pp obj} to contain #{mu_pp exp_substr}" }
    assert_respond_to obj, :include?
    assert obj.include?(exp_substr), msg
  end
end
改编自原始assert_match来源.这实际上也适用于阵列!
assert_contains 3, [1,2,3]
有assert_includes:
assert_includes 'foobar', 'foo'
将断言foobar包含foo.
| 归档时间: | 
 | 
| 查看次数: | 19227 次 | 
| 最近记录: |