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


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 }

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

The response of the request is as follows:

   "birthday":"2014-07 -01T04:30:00.000Z"

I am using RSpec 3.3.0 and Rails 4.2.3


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)

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

Scroll to Top