最小警告:已弃用 must_match 的全局使用。使用`_(obj)`

Minitest warning: DEPRECATED global use of must_match. Use `_(obj)`

我正在使用 Minitest 5.12.0 编写以下测试:

require 'minitest/autorun'
require 'nokogiri'
require 'net/http'

class NetClass; end

describe NetClass do
  attr_accessor :uri, :net
  before do
    @uri=URI('http://example.com/index.html')
    @net=Net::HTTP.get(uri)
  end

  it 'gets uri' do
    net.must_match /Example Domain/i
  end
end

测试成功但输出警告:

DEPRECATED: global use of must_match from net_test.rb:16 Use _(obj).must_match instead. This will fail in Minitest 6

为了消除警告,我更改了行:

net.must_match /Example Domain/i

_(net).must_match /Example Domain/i

我之前没有见过 _(obj) 语法,所以我的问题是 _() 在这种情况下做了什么。

这是 minitest 特定的功能。来自文档:

  # Returns a value monad that has all of Expectations methods
  # available to it.
  #
  # Also aliased to #value and #expect for your aesthetic pleasure:
  #
  #         _(1 + 1).must_equal 2
  #     value(1 + 1).must_equal 2
  #    expect(1 + 1).must_equal 2

因此,它是一个将所有需要的测试方法添加到您的对象的包装器。

执行如下:

  def _ value = nil, &block
    Minitest::Expectation.new block || value, self
  end

您可以深入研究资源 here