Ruby on rails RubyonRails-使用test:unit编写测试用例时需要帮助

Ruby on rails RubyonRails-使用test:unit编写测试用例时需要帮助,ruby-on-rails,testunit,Ruby On Rails,Testunit,我是RubyonRails新手。 我已经创建了一个示例应用程序,其中我使用rails test:unit编写了测试用例 现在,我无法找到一种使用test:unit测试http API调用的方法 在我的模型中有两种方法,一种是从API获取响应,另一种是将请求(JSON数据)发布到API。以下是我的方法 类RestApi def自我要求安全(apiMethod,qryString) uri=uri.parse(“https://test.my-api.com/test.json?apiKey=abc

我是RubyonRails新手。 我已经创建了一个示例应用程序,其中我使用rails test:unit编写了测试用例

现在,我无法找到一种使用test:unit测试http API调用的方法

在我的模型中有两种方法,一种是从API获取响应,另一种是将请求(JSON数据)发布到API。以下是我的方法 类RestApi def自我要求安全(apiMethod,qryString) uri=uri.parse(“https://test.my-api.com/test.json?apiKey=abc1234&userId=123456))

结束

def self.postSecure @主机='localhost' @端口='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}"
结束
结束

如果您想知道测试失败的原因,可能是因为
:new\u password
:confirm\u password
的值不匹配

关于一本好书,我可以推荐这本:它详细介绍了测试,是学习TDD的一个很好的资源。实际上,我用它来学习TDD,它对我帮助很大

后来我决定使用RSpec和Cucumber进行测试,主要是因为另外两本书(http://pragprog.com/titles/achbd/the-rspec-book 及)

编辑:

如果要测试失败条件,post后面的行应该是

assert_nil @user
assert_template :change_password
此外,为了清晰起见,您的测试名称应该类似于
test\u password\u change\u failure


原始测试中的最后一行不应该出现:这不是控制器应该做的。

实际上,尽管my:new\u密码和:confirm\u密码不匹配,但我的测试用例仍然正常通过。基本上我想要的是,我想测试我的change_password方法是否符合所有if-else条件。我认为我的测试用例与我的实际方法场景不兼容。
assert_nil @user
assert_template :change_password