【问题标题】:Ruby on Rails - help needed in writting test cases usinng test:unitRuby on Rails - 使用 test:unit 编写测试用例需要帮助
【发布时间】:2011-09-18 16:51:09
【问题描述】:

我是 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 = '本地主机' @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}"

结束 结束

【问题讨论】:

    标签: ruby-on-rails testunit


    【解决方案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/)。

    编辑:

    如果你想测试失败的条件,post 之后的行应该是这样的

    assert_nil @user
    assert_template :change_password
    

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

    原始测试中的最后一行不应该在那里:这不是你的控制器应该做的。

    【讨论】:

    • 实际上虽然我的 :new_password 和 :confirm_password 不匹配,但我的测试用例仍然可以正常通过。基本上我想要的是,我想针对所有 if else 条件测试我的 change_password 方法。在代码中给出,我认为我的测试用例与我的实际方法场景不兼容。