0

I have written an api for topics controller which will do all the crud operations.I need to test the api using Rspec. For the index action i have written a test case for http status.Further i need to check weather the index page is rendered correctly.Topic Api controller for index action is like this:

class Api::V1::TopicsController < ApplicationController
  def index
    @topics = Topic.all
    render json: @topics,status: 200
  end
end

Rspec for topic controller index action is:

RSpec.describe Api::V1::TopicsController do
describe "GET #index" do
before do
  get :index
end
it "returns http success" do
  expect(response).to have_http_status(:success)
  ////expect(response).to render_template(:index)
end
end
end

When run the testing it showing error message for the above line of code that i mentioned in comments.

Api::V1::TopicsController GET #index returns http success
 Failure/Error: expect(response).to render_template(:index)
   expecting <"index"> but rendering with <[]>

How to resolve it? error:

  TypeError: no implicit conversion of String into Integer

0) Api::V1::TopicsController GET #index should return all the topics
   Failure/Error: expect(response_body['topics'].length).to eq(2)

   TypeError:
   no implicit conversion of String into Integer
1
  • You should not be testing your views when you are controller is rendering json response . You should check for response status, also, make use of stub to stub your response and compare against your request and expected response. Commented Sep 3, 2018 at 8:25

1 Answer 1

0

You can test your API response for your controller actions, just a reference for your index action.

describe TopicsController do

  describe "GET 'index' " do

    it "should return a successful response" do
      get :index, format: :json
      expect(response).to be_success
      expect(response.status).to eq(200)
    end

    it "should return all the topics" do
      FactoryGirl.create_list(:topic, 2)
      get :index, format: :json
      expect(assigns[:topics].size).to eq 2
    end

  end

end
Sign up to request clarification or add additional context in comments.

10 Comments

what does it mean create_list in your code
If you want to create an object multiple times, it's the same as 2.times {FactoryGirl.create(:topic)}
When I run the tests that you provided it throwing error "no implicit conversion of String into Integer"
Which line ? Can you update your OP with the errors ?
OP means what???
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.