简体   繁体   中英

Ruby on Rails - help needed in writting test cases usinng test:unit

I am new to Ruby on Rails. I have created an sample app where I have written test cases using rails test:unit.

Now I am not able to find a way to test my http API calls using test:unit.

I have two method in my model, one is to GET response from API and another to POST request(JSON data) to API. Here are my methods as follows

class 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

end

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}"

end end

If you're wondering why your test is failing, it might be because the :new_password and :confirm_password values don't match.

Regarding a good book, I can recommend this one: http://pragprog.com/titles/nrtest/rails-test-prescriptions it covers testing in detail, and is a great resource to learn TDD. I actually used it to learn TDD, and it helped me a lot.

I've since decided to use RSpec and Cucumber for testing, mainly due to 2 other books (http://pragprog.com/titles/achbd/the-rspec-book and http://www.manning.com/katz/ ).

EDIT:

If you want to test the failing condition, the line after post should be something like

assert_nil @user
assert_template :change_password

In addition, for clarity's sake, your test name should be something like test_password_change_failure .

The last line in your original test shouldn't be there: that's not what your controller is supposed to be doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM