对于Web编程,数字以字符串形式出现.但to_i将其转换"5abc"到5和"abc"到0,这两个错误的答案.为了抓住这些,我写道:
def number_or_nil( s )
number = s.to_i
number = nil if (number.to_s != s)
return number
end
Run Code Online (Sandbox Code Playgroud)
有没有更整洁,更自然的方式来实现这种转换,并检测到字符串不是一个数字?
为了测试,我将 Rack::Request 直接发送到应用程序,而不是使用服务器。
def request_via_API( app, method, path, params={} ) # app should be API
env = Rack::MockRequest.env_for( path, {:method => method, :params=>params} )
app.handle Rack::Request.new(env)
end
Run Code Online (Sandbox Code Playgroud)
非常适合测试直接输入,但我被文件上传所困扰。我的真实系统通过文件上传在浏览器中运行良好。但是现在我想通过 API 对其进行测试,并且不知道如何通过任何 Rack 类/方法将文件内容放入请求中。(我尝试理解 Rack::Test::UploadedFile 但没有成功)。
谢谢,阿利斯泰尔