Minitest规格自定义匹配器

And*_*ite 6 ruby minitest

我的测试中有一条线:

page.has_reply?("my reply").must_equal true
Run Code Online (Sandbox Code Playgroud)

并使其更具可读性我想使用自定义匹配器:

page.must_have_reply "my reply"
Run Code Online (Sandbox Code Playgroud)

基于https://github.com/zenspider/minitest-matchers的文档,我希望我需要编写一个类似于以下内容的匹配器:

def have_reply(text)
  subject.has_css?('.comment_body', :text => text)
end
MiniTest::Unit::TestCase.register_matcher :have_reply, :have_reply
Run Code Online (Sandbox Code Playgroud)

问题是我无法看到如何获得对主题的引用(即页面对象).文档说"注释主题必须是断言中的第一个参数",但这并没有真正帮助.

hs-*_*hs- 6

有一个小例子,你可以创建应该响应设置方法的类matches?,failure_message_for_should,failure_message_for_should_not.在matches?方法中,您可以获得对主题的引用.

class MyMatcher
  def initialize(text)
    @text = text
  end

  def matches? subject
    subject =~ /^#{@text}.*/
  end

  def failure_message_for_should
    "expected to start with #{@text}"
  end

  def failure_message_for_should_not
    "expected not to start with #{@text}"
  end
end

def start_with(text)
  MyMatcher.new(text)
end
MiniTest::Unit::TestCase.register_matcher :start_with, :start_with

describe 'something' do
  it 'must start with...' do
    page = 'my reply'
    page.must_start_with 'my reply'
    page.must_start_with 'my '
  end
end
Run Code Online (Sandbox Code Playgroud)