0

尝试编写应该是一个简单的 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:
4

1 回答 1

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

在没有任何东西告诉 rails 要渲染什么的情况下@commentablenil它会尝试为创建操作渲染默认模板。这是Missing template comments/create从哪里来的。

我的意思else是:

  def create
    if @commentable
      [...]
    else
      head 404
    end
  end
于 2013-10-16T15:19:41.597 回答