为什么测试失败时这个Ruby代码会执行?
问题描述:
我试图以确保变量的值,然后再继续非零 - 值异步实例化取决于请求活动在西纳特拉实例为什么测试失败时这个Ruby代码会执行?
attr_accessor :access_token
until [email protected]_token.nil?
@access_token = RestClient.get @callback_URI + '/access_token/' + @request_Id
end
puts @access_token #=> always get output even if @access_token is nil
我的理解是表达的意思是:“保持分配RestClient调用@access_token的值直到它返回一个非零值,然后退出until块'。我做错了什么?非常感谢!
答
我不知道你的服务器的回报,但我会尝试像,
while true
begin
@access_token = RestClient.get @callback_URI + '/access_token/' + @request_Id
break if @access_token.code == 200
rescue
$stderr.puts "failed to get access token"
end
sleep 1
end
答
假设您正在使用剩余客户端gem,RestClient
不会在失败的请求上返回nil
。例如:
require 'rest_client'
puts RestClient.get "http://invalidurl.foo/somepath"
从我的供应商(不nil
)产生一个错误页:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
<title>T-Online Navigationshilfe</title>
</head>
<frameset rows="100%">
<frame src="http://navigationshilfe.t-online.de/dnserror?url=http://invalidurl.foo/"
frameborder="0" noresize="noresize"/>
<noframes>
<body>
<h1>Willkommen bei T-Online</h1>
<p>
<a href="http://navigationshilfe.t-online.de/dnserror?url=http://invalidurl.foo/">
weiter....</a>
</p>
</body>
</noframes>
</frameset>
</html>
没有这个代码产生的错误信息的互联网连接:
http.rb:762:in `initialize': getaddrinfo: nodename nor servname provided, or not known (SocketError)
这意味着,你的until
- 块总是只执行一次,因为RestClient#get
总是有返回值或抛出错误。为了帮助你,我需要了解你想要完成的更多细节。
轮询不是异步的想法... – Reactormonk 2012-03-27 11:40:55
为什么'直到!'而不是'while'? – 2012-03-27 11:48:38
@MichaelKohl @MichaelKohl我一定是一个悲观主义者:)同样的结果,尽管'while虽然.. @塔斯同意,最终将重构这与通知 – Kevsy 2012-03-27 13:34:49