我在考试中有一句话:

page.has_reply?("my reply").must_equal true

为了使它更具可读性,我想使用自定义匹配器:
page.must_have_reply "my reply"

基于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

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

最佳答案

有一个小例子,您可以创建一个类,它应该响应一组方法matches?failure_message_for_shouldfailure_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

关于ruby - Minitest规范自定义匹配器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12267332/

10-10 06:07