【发布时间】:2013-09-08 09:24:58
【问题描述】:
我在从控制器渲染 .json.erb 文件时遇到了最糟糕的情况,同时能够使用 RSpec 对其进行测试。我有 api_docs/index.json.erb 和以下控制器:
class ApiDocsController < ApplicationController
respond_to :json
def index
render file: 'api_docs/index.json.erb', content_type: 'application/json'
end
end
明确的render file 行似乎没有必要,但如果我不这样做或render template: 'api_docs/index.json.erb',则会收到有关“缺少模板api_docs/index”的错误。同样,如果我必须传递文件名,那么我必须提供确切的目录就更糟了——Rails 应该知道我的 ApiDocsController 模板位于 api_docs 目录中。
如果我有 render file 或 render template,那么我可以访问该页面并按预期获取我的 index.json.erb 文件的 JSON 内容。但是,此 RSpec 测试失败:
let(:get_index) { ->{ get :index } }
...
describe 'JSON response' do
subject {
get_index.call
JSON.parse(response.body)
}
it 'includes the API version' do
subject['apiVersion'].should_not be_nil
end
end
它在JSON.parse(response.body) 行上失败,如果我raise response.body,它是一个空字符串。如果我在控制器中执行render json: {'apiVersion' => '1.0'}.to_json,那么测试就可以通过了。
那么,当我转到 /api_docs 时,如何始终呈现 JSON 模板(无需将 .json 放在 URL 的末尾),并且以一种在浏览器和我的 RSpec 测试中都有效的方式?我是否可以渲染模板而不必进行一些长时间的render 调用,在其中我传递视图的完整路径?
【问题讨论】:
-
我想知道这是否不能回答你的问题:stackoverflow.com/questions/10681816/…
-
我在一分钟前发现它有帮助:我可以转到 /api_docs 而不是 /api_docs.json 并在浏览器中查看 JSON,但 RSpec 测试仍然失败,因为
response.body是空字符串。 -
This RSpec issue 可能是相关的。
标签: ruby-on-rails json rspec ruby-on-rails-4