ruby-on-rails-4capybararspec-railsfabrication-gem

How to test the keys and values of api response for Request specs


I am writing Request specs, and having trouble with to test api respond in json formate. I am using capybara and fabricator, here is my code which i trying...

    context 'discounts in api' do
      let(:user) { Fabricate(:user, activated: true) }
      let(:api_token) { user.api_token }

      before { visit api_url_for('/v1/discount_coupons', api_token) }

      it 'returns coupons collection' do
        Fabricate(:discount_coupon, code: 'Discount One', global: true)

        save_screenshot("tmp/capybara/screenshot-#{Time::now.strftime('%Y%m%d%H%M%S%N')}.png")
        save_and_open_page


        expect(json_response['total_records']).to eq 1
        expect(json_response['total_pages']).to eq 1
        expect(json_response['page']).to eq 0
        expect(json_response['discount_coupons'].size).to eq 1
        expect(json_response['discount_coupons'][0]['code']).to eq 'Discount One'
      end
end

the responce i getting is this

{"discount_coupons":[{"id":11,"code":"Discount One","type":"DiscountPercentage","amount_off":1.5,"global":true,"expires_on":null,"vendors":[]}],"page":0,"total_pages":1,"total_records":1}

and error goes to stop me for run a successful test,

Failure/Error: expect(json_response['total_pages']).to eq 1
             NoMethodError:
               undefined method `body' for nil:NilClass 

I think my expect to json_response is wrong or something missing, can somone help me to do it handsome way please, hint to that how can i test using key and value.


Solution

  • Best way to test an API is use rspec as you just need to do this:

    it "should return the expected information" do
      get "/url"
    
      parsed_response = JSON.parse(response.body)
      expect(parsed_response["key"]).to eq(whatever)
    end
    
    it "should update the expected entity" do
      post "/url", body, headers
    
      parsed_response = JSON.parse(response.body)
      expect(parsed_response["key"]).to eq(whatever)
    end
    

    And your tests are failing because you are trying to parse a response that is empty. The Fabric can be failing or the call might be wrong.