Webmock:如何伪造 gzipped 响应?

Webmock: how to fake a gzipped response?

我在存根方面没有太多经验,并且在向 Braintree using webmock and braintree-rails 发送请求时遇到问题。

spec/spec_helper.rb

RSpec.configure do |config|
  config.include(ConnectionHelper)

  config.before(:each) do
    stub_request(:post, /.*braintree.*/).
    with(braintree_hash).to_return(gzipped_response)
  end
end

spec/support/connection_helper.rb

def gzipped_response
  {
    status: 200,
    body: "\u001F\x8B\b[=11=]:\x87GU[=11=]\u0003\u0003[=11=][=11=][=11=][=11=][=11=][=11=][=11=][=11=][=11=]",
    headers: {}
  } 
end

def braintree_hash
  { :body => /.*/,
    :headers => {'Accept'=>'application/xml', 'Content-Type'=>'application/xml',
    'User-Agent'=>'Braintree Ruby Gem 2.42.0 (braintree-rails-1.4.0)',
    'X-Apiversion'=>'4'}
  }
end

Rspec 错误:

2) Content: when ordering content show page has relevant information 
     Failure/Error: click_button "Order"
     Braintree::UnexpectedError:
       expected a gzipped response
     # ./app/classes/payment.rb:13:in `generate_token'
     # ./app/controllers/posts_controller.rb:44:in `pay'
     # ./spec/features/content_spec.rb:251:in `block (4 levels) in <top (required)>'

我正在尝试测试页面,而不是付款本身,但是在呈现页面时需要先检索令牌,所以我收到了这个错误。

我将如何伪造 gzip 响应,或者在我的测试中跳过与 Braintree 请求有关的任何事情?

app/controllers/posts_controller.rb

def pay
  @post = Post.find(params[:id])
  @client_token = Payment.new(current_user).generate_token
end

app/classes/payment.rb

class Payment    
  def initialize(customer)
    @customer = customer
    @customer_id = @customer.id
  end

  def generate_token
    Braintree::ClientToken.generate(customer_id: @customer_id)
  end   
end

我在布伦特里工作。如果您对我们的 API 和客户端库有任何疑问,您可以随时 reach out to our support team.

您的存根响应正文需要压缩。您可以像这样创建一个空的压缩字符串:

irb(main):010:0> require 'stringio' 
=> false
irb(main):011:0> require 'zlib'
=> false
irb(main):012:0> Zlib::GzipWriter.new(StringIO.new("w")).close.string
=> "\u001F\x8B\b[=10=]:\x87GU[=10=]\u0003\u0003[=10=][=10=][=10=][=10=][=10=][=10=][=10=][=10=][=10=]"

那么试试你的 status_ok 方法:

def status_ok
  {
    status: 200,
    body: "\u001F\x8B\b[=11=]:\x87GU[=11=]\u0003\u0003[=11=][=11=][=11=][=11=][=11=][=11=][=11=][=11=][=11=]",
    headers: {"Content-Encoding" => "gzip"}
  } 
end