Specifying Content Type in rspec

前端 未结 7 1749
终归单人心
终归单人心 2021-01-01 12:57

I\'m trying to build an rspec test that sends JSON (or XML) via POST. However, I can\'t seem to actually get it working:

    json = {.... data ....}.to_json
         


        
7条回答
  •  庸人自扰
    2021-01-01 13:44

    First of all, you don't want to test the built-in conversion of json to hash. Same applies to xml.

    You test controller with data as hashes, not bothering wether it's json, xml or from a html form.

    But if you would like to do that as an exercise, this is a standalone ruby script to do play with :)

    require 'json'
    url = URI.parse('http://localhost:3030/mymodels.json')
    request = Net::HTTP::Post.new(url.path)
    request.content_type="application/json"
    request.basic_auth('username', 'password')  #if used, else comment out
    
    hash = {:mymodel => {:name => "Test Name 1", :description => "some data for testing description"}}
    request.body = hash.to_json
    response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}
    puts response
    

    to switch to xml, use content_type="text/xml" and

    request.body = "Test Name 1Some data for testing"
    

提交回复
热议问题