简体   繁体   English

使用 minitest 测试正则表达式

[英]Testing a regular expression with minitest

Assuming a shared method like:假设共享方法如下:

  def sanitize_spaces(dirty_attribute)
    dirty_attribute = dirty_attribute.gsub(/\s+/, "")
  end

what kind of a minitest should be written?应该写什么样的迷你测试? Naturally, one could test the method that calls this method, but that sort of buries the test within another.自然地,可以测试调用此方法的方法,但这种做法会将测试埋在另一个方法中。 The goal is to have a mechanism to test this individual method on its own.目标是拥有一种机制来自行测试这个单独的方法。

I don't think this method should be public (presumably you're just trying to give a name to a piece of logic so that it is easier to read), and if it is not public then I would not test it (you're testing implementation details).我不认为这个方法应该是公开的(大概你只是想给一段逻辑起个名字以便于阅读),如果它不是公开的那么我就不会测试它(你'重新测试实施细节)。

But if the sanitize code you give is an example of some larger piece of logic, or it's a widely used helper method you could do something like this:但是如果你给出的清理代码是一些更大的逻辑的例子,或者它是一个广泛使用的辅助方法,你可以这样做:

(I assume that the method is wrapped in a class called MySanitizer ) (我假设该方法被包装在一个名为MySanitizer的 class 中)

require "minitest/autorun"

class TestMySanitizer < Minitest::Test
  def setup
    @sanitizer = MySanitizer.new
  end

  def test_that_return_value_is_correct
    string_to_be_sanitized = "O H A I  \t\t\n   !"
    assert_equal "OHAI!", sanitizer.sanitize_spaces(string_to_be_sanitized)
  end

  def test_that_nowhitespace_input_is_unaffected
    nowhitespace = "OHAI!"
    assert_equal nowhitespace, sanitizer.sanitize_spaces(nowhitespace)
  end
end

Theoretically you could go further and have tests that include every form of whitespace and non-whitespace character, but your testing (automated or otherwise) is unlikely to be better than that which is already in place in the Ruby standard library for gsub, so it is not particularly useful to verify anything beyond the fact that there is something there which affects whitespace.从理论上讲,您可以 go 进一步进行测试,包括各种形式的空白和非空白字符,但您的测试(自动或其他方式)不太可能比 Ruby gsub 标准库中已有的测试更好,因此它除了那里有影响空白的东西之外,对于验证任何东西都不是特别有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM