Specifying Content Type in rspec

前端 未结 7 1706
终归单人心
终归单人心 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:38

    A lot of frustration and variations and that's what worked for me. Rails 3.2.12 Rspec 2.10

     @request.env["HTTP_ACCEPT"] = "application/json"
     @request.env["CONTENT_TYPE"] = "application/json"
     put :update, :id => 1, "email" => "bing@test.com"
    
    0 讨论(0)
  • 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 = "<?xml version='1.0' encoding='UTF-8'?><somedata><name>Test Name 1</name><description>Some data for testing</description></somedata>"
    
    0 讨论(0)
  • 2021-01-01 13:46

    The best way that I have found to test these things is with request tests. Request tests go through the full param parsing and routing stages of Rails. So I can write a test like this:

    request_params = {:id => 1, :some_attribute => "some value"}
    headers = {'Accept' => 'application/json', 'Content-Type' => 'application/json'}
    put "/url/path", request_params.to_json, headers
    expect(response).to be_success
    
    0 讨论(0)
  • 2021-01-01 13:48

    I think that you can specify the headers with headers param:

    post '/model1.json', headers: {'Content-type': 'application/json'}
    

    Following the Rspec documentation of how provide JSON data.

    0 讨论(0)
  • 2021-01-01 13:52

    A slightly more elegant test is to use the header helper:

    header "HTTP_ACCEPT", "application/json"
    json = {.... data ....}.to_json
    post '/model1.json', json
    

    Now this does exactly the same thing as setting @env; it's just a bit prettier.

    0 讨论(0)
  • 2021-01-01 13:53

    There's a way to do this described in this thread -- it's a hack, but it seems to work:

    @request.env["HTTP_ACCEPT"] = "application/json"
    json = { ... data ... }.to_json
    post :create, :some_param => json
    
    0 讨论(0)
提交回复
热议问题