【问题标题】:Rspec String argument constraint to match multiple regexRspec 字符串参数约束以匹配多个正则表达式
【发布时间】:2017-10-23 18:23:46
【问题描述】:

如何传递与多个正则表达式约束匹配的参数约束?

expect(subject).to(
  receive(:matching_multiple_regex)
  .with( a_string_that_matches_all[/hello/, /world/])
)

subject.matching_multiple_regex('hello /o\ world')
# => should pass

如何实现a_string_that_matches_all[/hello/, /world])

编辑我的具体用例:我正在尝试为松弛消息实现匹配器

expect { some_code }.to(
      send_a_slack_notification
      .with_message_containing("Hello world")
      .with_link_to('hello_world')
    )

send_a_slack_notification 是一个自定义匹配器 expect(SlackService).to receive(ping) 并接受链参数: - with_message_containing 预计会运行一个简单的字符串正则表达式匹配 - with_link_to预计会运行一个松弛的 href 匹配

我现在正在处理的代码看起来像

require 'rspec/expectations'

RSpec::Matchers.define :send_a_slack_notification do
  supports_block_expectations

  match do |actual|
    slack_spy = spy(SlackConnector)
    stub_const('SlackConnector', slack_spy)
    expectation_hash = {}
    expectation_hash[:channel] = @channel if @channel

    actual.call

    expect(slack_spy).to(
      have_received(:ping)
      .with(
        a_string_that_matches_all([@text, @link_regexp].compact)),
        hash_including(expectation_hash)
      )
    )
  end

  chain :with_message_containing do |text|
    @text = text
  end

  chain :with_link_to do |href, text = nil|
    @link_regexp = /<.*#{::Regexp.escape(href)}.*\|#{text ? ::Regexp.escape(text) : '.+' }>/
  end

  chain :to_channel do |channel|
    @channel = channel
  end
end

【问题讨论】:

    标签: ruby-on-rails rspec ruby-on-rails-5 rspec3


    【解决方案1】:

    您或许可以创建自己的custom matcher 以按照您的要求匹配多个正则表达式。不过,我建议您改为使用单个正则表达式。

    expect(subject).to match(/^hello.+world$/)
    

    【讨论】:

    • 嘿,我在用例中添加了一个具体示例。特别是我想在同一个参数上分别测试链接和文本的存在,所以我认为我需要不同的正则表达式才能使其可读。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多