如何忽略rspec VCR中特定主机的请求正文匹配?

时间:2019-03-25 21:44:22

标签: ruby-on-rails ruby rspec rubygems vcr

我将Rails应用程序与ElasticSearch和Kibana集成在一起,并且我将它们用于记录和衡量对外部API的请求。我不希望VCR与ElasticSearch请求记录的正文匹配,因为每个日志中都有一个“当前时间”(created_at)字段,这会打破VCR的较早记录。

这是我当前的配置

VCR.configure do |c|
  c.ignore_localhost = true
  c.cassette_library_dir = 'spec/fixtures/vcr_cassettes'

  vcr_mode = ENV['VCR_MODE'] =~ /rec/i ? :all : :once

  c.hook_into :webmock
  c.default_cassette_options[:record] = vcr_mode
  c.configure_rspec_metadata!
end

这是我的自定义REST客户端中的日志方法。

  def log(method, params, response, comments:)
    Rails.logger.info(response.inspect)

    Elastic::LogServices
      .log_request(comments,
                   method: method,
                   source: ENV['HOSTNAME'],
                   url: response.env.url.to_s,
                   header: response.env.request_headers,
                   body: params,
                   type: :out,
                   response_header: response.headers,
                   response_body: response.body,
                   response_status: response.status)
  end

在日志服务中...

    def self.log_request(comments = '',
                         created_at: nil,
                         method:,
                         source:,
                         url:,
                         header:,
                         body:,
                         type:,
                         response_header:,
                         response_body: '?',
                         response_status:,
                         format: 'REST')
      log =
        Elastic::Request::Log
        .new(created_at: created_at,
             method: method,
             source: source,
             url: url,
             header: header,
             body: JSON.pretty_generate(body),
             type: type,
             response:
              {
                header: response_header,
                body: JSON.pretty_generate(response_body),
                status: response_status
              },
             format: format,
             comments: comments)

      Elastic::Request::LogJob.perform_async(log)
    end

该字段在日志实体类中

        @created_at = created_at || Time.now.utc.iso8601

此外,我不想模拟“ Time.now.utc.iso8601”方法,因为有很多测试需要更改。该应用程序对其他API进行了大量请求。

是否将VCR配置为忽略所有“ elasticsearch:9200”请求的车身匹配?

1 个答案:

答案 0 :(得分:1)

您可以尝试:

VCR.configure do |c|
  c.ignore_localhost = true
  c.cassette_library_dir = 'spec/fixtures/vcr_cassettes'
  c.register_request_matcher :body do |request1, request2|
    if request1.uri.include?('<your_host>')
      true
    else
      CGI.escape(request1.body) == CGI.escape(request2.body)
    end
  end

  c.hook_into :webmock
  c.configure_rspec_metadata!
end