Reputation: 11
I'm currently putting together a project on Rails (4.1.8) and am trying out writing RSpec request specs to test the api routes. Strangely however it also seems to return a empty response when running the test, however doing a direct request with Postman returns the json data as expected.
Request Spec:
# spec/requests/tasks_spec.rb
require 'rails_helper'
RSpec.describe 'Tasks API', type: :request do
render_views
describe 'GET /tasks' do
it 'returns tasks' do
headers = {
"ACCEPT" => "application/json"
}
get '/tasks', headers
puts "Response: #{response}"
expect(response.content_type).to eq("application/json")
expect(json).not_to be_empty
end
end
end
Result:
Failure/Error: expect(json).not_to be_empty
expected `[].empty?` to return false, got true
The Tasks Controller is setup as follows:
class TasksController < ApplicationController
before_action :set_task, only: [:show, :update, :destroy]
# GET /tasks
def index
@tasks = Task.all
json_response(@tasks)
end
Response Concern:
module Response
def json_response(object, status = :ok)
render json: object, status: status
end
end
Spec Support:
module RequestSpecHelper
# Parse JSON response to ruby hash
def json
JSON.parse(response.body)
end
end
I had read similar questions which talk about a rende_views fix - however I've added that with no effect and also I thought you didn't need these when using Request specs as they should run through the full stack? Can anyone shed some light, quite new to request specs and a bit puzzled.
Upvotes: 1
Views: 2560
Reputation: 3251
There is no tasks
in your DB, that's why it is returning an empty array.
You need to create a task
before calling index
action.
Either you can create a factory using the facatory_girl_rails gem for Task
or you can call the create
action of TasksController
before calling index
action:
# spec/requests/tasks_spec.rb
require 'rails_helper'
RSpec.describe 'Tasks API', type: :request do
render_views
describe 'GET /tasks' do
before do
FactoryGirl.create(:task)
end
it 'returns tasks' do
headers = {
"ACCEPT" => "application/json"
}
get '/tasks', headers
puts "Response: #{response}"
expect(response.content_type).to eq("application/json")
expect(json).not_to be_empty
end
end
end
Reference FactoryGirl(Defining factories): https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#defining-factories
Upvotes: 1