尝试编写应该是简单的RSpec测试,并设置我的创建操作以呈现JSON,如下所示:
require 'spec_helper'
describe CommentsController do
let(:valid_attributes) do
{
title: 'First Comment', comment_text: 'LoremIpsum', commentable_id: 1,
user_id: 1, entered_by: 'john', last_updated_by: 'doe'
}
end
context 'JSON' do
describe 'POST create' do
describe 'with valid params' do
it 'creates a new Comment' do
json = {:format => 'json', :comment => valid_attributes}
post :create, json
end
it 'assigns a newly created comment as @comment' do
json = {:format => 'json', :comment => valid_attributes}
post :create, json
assigns(:comment).should be_a(Comment)
assigns(:comment).should be_persisted
end
end
end
end
end
但是我得到以下输出:
ActionView::MissingTemplate: Missing template comments/create, application/create with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee, :haml]}. Searched in:
答案 0 :(得分:0)
else
为零时,你错过了@commentable
部分。这将尝试渲染默认模板!
澄清:
这是最初发布的内容:
def create
if @commentable
@comment = @commentable.comments.new(comment_params)
if @comment.save
render json: @comment, status: :created
else
render json: @comment.errors, status: :unprocessable_entity
end
end
end
在@commentable
为nil
的情况下,没有任何内容告诉rails要呈现的内容,因此它将尝试呈现create动作的默认模板。这是Missing template comments/create
的来源。
我对else
部分的意思是:
def create
if @commentable
[...]
else
head 404
end
end