【发布时间】:2017-03-13 08:53:27
【问题描述】:
我目前正在 Rails (4.1.8) 上编写一个项目,并正在尝试编写 RSpec 请求规范来测试 api 路由。然而奇怪的是,在运行测试时它似乎也返回了一个空响应,但是使用 Postman 进行直接请求会按预期返回 json 数据。
请求规范:
# 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
结果:
Failure/Error: expect(json).not_to be_empty
expected `[].empty?` to return false, got true
Tasks Controller 设置如下:
class TasksController < ApplicationController
before_action :set_task, only: [:show, :update, :destroy]
# GET /tasks
def index
@tasks = Task.all
json_response(@tasks)
end
回应关注:
module Response
def json_response(object, status = :ok)
render json: object, status: status
end
end
规格支持:
module RequestSpecHelper
# Parse JSON response to ruby hash
def json
JSON.parse(response.body)
end
end
我读过类似的问题,其中讨论了 rende_views 修复 - 但是我添加了没有效果,而且我认为您在使用请求规范时不需要这些,因为它们应该贯穿整个堆栈?任何人都可以阐明一些新的要求规格并且有点困惑。
【问题讨论】:
-
添加
puts "All tasks: #{Task.count}"并检查输出,我很确定您的测试数据库是空的。
标签: ruby-on-rails ruby rspec