【发布时间】: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