gpt4 book ai didi

ruby - Minitest 规范自定义匹配器

转载 作者:数据小太阳 更新时间:2023-10-29 07:05:46 25 4
gpt4 key购买 nike

我的测试中有一行:

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_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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com