How to check for a JSON response using RSpec?

后端 未结 14 1312
谎友^
谎友^ 2020-11-29 16:03

I have the following code in my controller:

format.json { render :json => { 
        :flashcard  => @flashcard,
        :lesson     => @lesson,
             


        
14条回答
  •  孤街浪徒
    2020-11-29 16:42

    For Your JSON response you should parse that response for expected results For Instance: parsed_response = JSON.parse(response.body)

    You can check other variables which is included in response like

    expect(parsed_response["success"]).to eq(true)
    expect(parsed_response["flashcard"]).to eq("flashcard expected value")
    expect(parsed_response["lesson"]).to eq("lesson expected value")
    expect(subject["status_code"]).to eq(201)
    

    I prefer also check keys of JSON response, For Example:

    expect(body_as_json.keys).to match_array(["success", "lesson","status_code", "flashcard"])
    

    Here, We can use should matchers For expected results in Rspec

提交回复
热议问题