3

我有以下代码生成用于测试内部 Restful API 身份验证的哈希。

问题是生成的哈希返回转义值。

json_headers方法应返回如下内容:

{"Authorization"=>"Basic ZnBfZXJwOllrdGh4aHRSZTZWM1d1d09oeVlmcW0xTg==", "Accept"=>"application/json"} 

但是正在返回:

{\"Authorization\"=>\"Basic ZnBfZXJwOllrdGh4aHRSZTZWM1d1d09oeVlmcW0xTg==\\n\", \"Accept\"=>\"application/json\"}

有谁知道从 Ruby 哈希返回原始键/值的简单方法?

这是代码:

module ERP
  class CustomersMock

    def json_headers
      authorization_hash.merge("Accept"=>"application/json")
    end

    def authorization_hash 
      {"Authorization" => "Basic #{base64_user_pass}"}
    end

    def user_pass
       # user:password
       [ ERP_CONF['user'], ERP_CONF['password'] ].join(':')
    end

    def base64_user_pass
      Base64.encode64(user_pass)
    end

    def add(customer)
      customers << customer
    end        

    def customers
      []
    end         

    def run
      ActiveResource::HttpMock.respond_to do |mock|
        customers.each do |customer|
          mock.get "/customers/#{customer.id}.json", json_headers, customer.to_json
        end
      end
    end
  end
end

出于某种原因,如果我对标头散列进行硬编码,它们就可以工作,但是如果我调用该json_headers方法,该respond_to块会将它们转换为字符串并转义值。

这是 rspec 失败:

Could not find a response recorded for <GET: /api/customers/1011.json [{"Authorization"=>"Basic ZnBfZXJwOllrdGh4aHRSZTZWM1d1d09oeVlmcW0xTg==", "Accept"=>"application/json"}] ()> - Responses recorded are: ["<GET: /api/customers/1011.json [{\"Authorization\"=>\"Basic ZnBfZXJwOllrdGh4aHRSZTZWM1d1d09oeVlmcW0xTg==\\n\", \"Accept\"=>\"application/json\"}] ()>"]
4

2 回答 2

3

转义引号起初有点令人困惑。我猜你是从 IRB 或 Pry 等 REPL 测试这个。您的方法实际上包含普通的双引号——它们只是为了输出而转义,因为双引号已经用于表示字符串的开头和结尾。这意味着当您实际上想要将双引号字符存储"在字符串中时,您需要输入,"\""因为如果您正在输入""",您实际上会以第二个". 您可以通过实际打印字符串来查看“真正”包含的内容puts。让我用一个例子来证明这一点:

require 'json'

h = {a: 123, b: 456}

h.to_json
#=> "{\"a\":123,\"b\":456}"       # note the escaped double quotes

puts h.to_json
# {"a":123,"b":456}               # when printed, quotes are no longer escaped

double_quote_1 = '"'              # another way to store " in a string
double_quote_2 = "\""
double_quote_1 == double_quote_2  # both have the same contents, a single "
#=> true

json1 = '{"a":123,"b":456}'       # less confusing way of writing the json from above
json2 = "{\"a\":123,\"b\":456}"
json1 == json2
#=> true
于 2013-09-19T20:39:18.320 回答
0

这不是一个逃避问题。我认为这是基于 rspec 失败的测试输出:

Could not find a response recorded for 
<GET: /api/customers/1011.json [{"Authorization"=>"Basic ZnBfZXJwOllrdGh4aHRSZTZWM1d1d09oeVlmcW0xTg==", "Accept"=>"application/json"}] ()> 

- Responses recorded are: [
"<GET: /api/customers/1011.json [{\"Authorization\"=>\"Basic ZnBfZXJwOllrdGh4aHRSZTZWM1d1d09oeVlmcW0xTg==\\n\", \"Accept\"=>\"application/json\"}] ()>"
]

看起来唯一的区别是标头哈希在一个而不是另一个中被转义。

但是,它不会转义以“授权”值结尾的行,因此修复方法是删除该值:

def base64_user_pass
  Base64.encode64(user_pass).strip
end
于 2013-09-19T21:27:15.313 回答