ruby-on-rails – How can I test that a field exists in a response using RSpec?

Question:

I am testing for an API en RoR . I want to validate the structure of a response to a request from my API. I want to make sure that there is a particular field of that answer and if it does not exist indicate that the test fails.

let(:user) { FactoryGirl.create(:user) }

describe "POST #create" do

    context "when logged in with identifier" do

        before(:each) do
            @user_attributes = { identifier: user[:email], password: '12345678' } 
            post :create, { session: @user_attributes }
        end

        it"when is valid token" do
            #como valido que en la respuesta exista el token
        end
    end
end

The response of the request is as follows:

{"user": 
  {
   "id":9005,
   "email":"kayden_schmidt@pfeffer.co.uk",
   "first_name":"Serenity",
   "middle_name":"Keagan",
   "last_name":"O'Kon",
   "birthday":"2014-07 -01T04:30:00.000Z"
  },
 "token":"....."
 }

I am using RSpec 3.3.0 and Rails 4.2.3

Answer:

When you make a call to post, you get or should get a response object as a response . I recommend that you parse it to JSON to manipulate it better.

it "when is valid id" do
  expect(JSON.parse(response.body).first.keys.include?("id")).to be(true)
end

In general, the key is to parse as JSON and do something with the response.body object.

Scroll to Top