You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Minitest单独测试sanitize_spaces正则处理方法?

单独测试sanitize_spaces方法的Minitest用例

假设你的sanitize_spaces方法属于某个类(比如StringUtils),要单独测试它的话,直接写针对这个方法的Minitest用例就行,不用依赖其他调用它的方法。下面是具体的测试代码:

require 'minitest/autorun'

# 假设你的方法所在的类是StringUtils
class StringUtils
  def sanitize_spaces(dirty_attribute)
    dirty_attribute.gsub(/\s+/, "")
  end
end

class TestStringUtils < Minitest::Test
  def setup
    @utils = StringUtils.new
  end

  def test_sanitize_single_spaces
    assert_equal "helloworld", @utils.sanitize_spaces("hello world")
  end

  def test_sanitize_multiple_consecutive_spaces
    assert_equal "helloworld", @utils.sanitize_spaces("hello   world")
  end

  def test_sanitize_leading_and_trailing_spaces
    assert_equal "helloworld", @utils.sanitize_spaces("  hello world  ")
  end

  def test_sanitize_special_whitespace_characters
    # 覆盖制表符、换行符等空白字符
    assert_equal "helloworld", @utils.sanitize_spaces("hello\tworld\n")
  end

  def test_sanitize_empty_string
    assert_equal "", @utils.sanitize_spaces("")
  end

  def test_sanitize_nil_raises_error
    # 原方法传nil会报错,这里验证这个行为
    assert_raises(NoMethodError) do
      @utils.sanitize_spaces(nil)
    end
  end
end

测试说明:

  • 每个测试方法专注一个场景,确保覆盖所有可能的输入情况
  • setup方法提前初始化类实例,避免每个测试重复写创建代码
  • 不仅测试普通空格,还要覆盖连续空格、前后空格、特殊空白符(制表符、换行)这些边界情况
  • 空字符串和nil的情况也要考虑:空字符串处理后还是空,nil因为没有gsub方法会抛出错误,这个也要验证

如果你的sanitize_spaces是类方法(比如StringUtils.sanitize_spaces),那测试代码稍微调整,不用创建实例,直接调用类方法就行:

# 类方法版本的测试示例
def test_sanitize_single_spaces
  assert_equal "helloworld", StringUtils.sanitize_spaces("hello world")
end

这样就能完全单独测试这个方法本身,不用依赖其他业务逻辑,测试结果也更直接清晰。

内容的提问来源于stack exchange,提问作者Jerome

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 04:50:16