我是 Ruby on Rails 的新手。我创建了一个示例应用程序,我在其中使用 rails test:unit 编写了测试用例。
现在我找不到使用 test:unit 测试我的 http API 调用的方法。
我的模型中有两种方法,一种是从 API 获取响应,另一种是向 API 发布请求(JSON 数据)。这是我的方法如下
类 RestApi def self.reqSecure(apiMethod, qryString) uri = URI.parse("https://test.my-api.com/test.json?apiKey=abc1234&userId=123456")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
hashOfResponse = ActiveSupport::JSON.decode(response.body)
return hashOfResponse
结尾
def self.postSecure @host = 'localhost' @port = '8099'
@path = "/posts"
@body ={
"bbrequest" => "BBTest",
"reqid" => "44",
"data" => {"name" => "test"}
}.to_json
request = Net::HTTP::Post.new(@path, initheader = {'Content-Type' =>'application/json'})
request.body = @body
response = Net::HTTP.new(@host, @port).start {|http| http.request(request) }
puts "Response #{response.code} #{response.message}: #{response.body}"
结束结束