在Ruby单元测试中,如何断言字符串包含某些子字符串?

Lou*_*hys 24 ruby string unit-testing ruby-on-rails

在Ruby单元测试中,如何断言字符串包含子字符串?就像是:

assert_contains string_to_test, substring_to_verify
Run Code Online (Sandbox Code Playgroud)

Pat*_*ity 33

你可以去用assert_match pattern, string, [message]它,如果真string =~ pattern:

assert_match substring_to_verify, string_to_test
Run Code Online (Sandbox Code Playgroud)

例如

assert_match /foo/, "foobar"
Run Code Online (Sandbox Code Playgroud)

如果你经常使用它,为什么不写自己的断言?

require 'test/unit'

module Test::Unit::Assertions
  def assert_contains(expected_substring, string, *args)
    assert_match expected_substring, string, *args
  end
end
Run Code Online (Sandbox Code Playgroud)

或者,使用@IvayloStrandjev描述的方法(更容易理解),您可以定义

require 'test/unit'

module Test::Unit::Assertions
  def assert_contains(expected_substring, string, *args)
    assert string.include?(expected_substring), *args
  end
end
Run Code Online (Sandbox Code Playgroud)

用法完全按照您在问题中的要求使用,例如

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 Code Online (Sandbox Code Playgroud)

哪个会产生

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
Run Code Online (Sandbox Code Playgroud)

编辑

根据要求,使用自动消息:

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
Run Code Online (Sandbox Code Playgroud)

改编自原始assert_match来源.这实际上也适用于阵列!

assert_contains 3, [1,2,3]
Run Code Online (Sandbox Code Playgroud)


tro*_*skn 8

assert_includes

assert_includes 'foobar', 'foo'
Run Code Online (Sandbox Code Playgroud)

将断言foobar包含foo.

  • 格式应该是 `assert_includes result, 'foo'` 以测试子字符串 'foo'。 (3认同)

izo*_*ica 7

你可以写assert string_to_test.include?(string_to_verify)一下.你不能期望对你想要执行的所有检查都有断言,所以只需对布尔条件进行经典检查.

也可以看看这里看到所有可用断言的列表.