Webmock:如何伪造一个gzipped响应?

时间:2015-05-04 11:08:26

标签: ruby-on-rails ruby-on-rails-4 stub braintree webmock

我在使用Braintreewebmockbraintree-rails提出请求方面遇到问题时,我没有多少经验。

规格/ 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

规格/支持/ connection_helper.rb

def gzipped_response
  {
    status: 200,
    body: "\u001F\x8B\b\0:\x87GU\0\u0003\u0003\0\0\0\0\0\0\0\0\0",
    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)>'

我试图测试页面,而不是测试本身,但是在呈现页面时,需要首先检索令牌,因此我收到此错误。

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

应用程序/控制器/ posts_controller.rb

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

应用程序/类/ 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

1 个答案:

答案 0 :(得分:2)

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

你的存根响应体需要被压缩。您可以创建一个空的gzip压缩字符串,如下所示:

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\0:\x87GU\0\u0003\u0003\0\0\0\0\0\0\0\0\0"

请尝试使用status_ok方法:

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