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

时间:2011-06-20 13:22:21

标签: ruby-on-rails testunit

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

现在我无法使用test:unit。

找到测试我的http API调用的方法

我的模型中有两个方法,一个是来自API的GET响应,另一个是针对API的POST请求(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}"

端 端

1 个答案:

答案 0 :(得分:1)

如果您想知道测试失败的原因,可能是因为:new_password:confirm_password值不匹配。

关于一本好书,我可以推荐这本书:http://pragprog.com/titles/nrtest/rails-test-prescriptions它涵盖了详细的测试,是学习TDD的好资源。我实际上用它来学习TDD,这对我帮助很大。

我决定使用RSpec和Cucumber进行测试,主要是由于另外两本书(http://pragprog.com/titles/achbd/the-rspec-book和http://www.manning.com/katz/)。

编辑:

如果你想测试失败的条件,帖子之后的行应该是

assert_nil @user
assert_template :change_password

此外,为了清楚起见,您的测试名称应该类似于test_password_change_failure

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