ruby 扩展RSpec :: Matchers :: BuiltIn :: Match的自定义匹配器也可以指定捕获组。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 扩展RSpec :: Matchers :: BuiltIn :: Match的自定义匹配器也可以指定捕获组。相关的知识,希望对你有一定的参考价值。

module CustomMatchers
  class Match < RSpec::Matchers::BuiltIn::Match
    def matches?(actual)
      # first ensure the regex matched
      return false unless result = super
      # only continue if specifying captures
      return result unless expected_captures = @captures

      actual_captures = to_hash result

      RSpec::Matchers::BuiltIn::Include.new(expected_captures).matches?(actual_captures).tap do |captures_matched|
        # replace expected/actual regex with the matchdata
        # if the matchdata didn't match. this way we get a diff of the matchdata hashes
        # otherwise, leave untouched so the description is per normal
        unless captures_matched
          @expected = expected_captures
          @actual = actual_captures
        end
      end
    end

    def capturing(captures)
      @captures = captures
      self
    end

    private

    def to_hash(matchdata)
      Hash[matchdata.names.map(&:to_sym).zip matchdata.captures]
    end
  end

  def matchy(expected)
    Match.new expected
  end
end

以上是关于ruby 扩展RSpec :: Matchers :: BuiltIn :: Match的自定义匹配器也可以指定捕获组。的主要内容,如果未能解决你的问题,请参考以下文章

Rails无法加载shoulda-matchers 3.1.1 gem,undefined方法`allow_value'代表#

如何使用 Capybara Rspec Matchers 测试演示者?

ruby expectation_matchers_spec.rb

如何在Rspec中测试文件大小

ruby [rspec]“使用RSpec测试Rails程序”笔记

如何测试 RSpec 中的 attr_accessible 字段